-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
66 lines (54 loc) · 1.64 KB
/
user.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package users
import (
"fmt"
"time"
"github.com/bkasin/gogios"
"github.com/bkasin/gogios/helpers/config"
"github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt"
)
// CreateUser - Add a new user to configured gogios databases
func CreateUser(user gogios.User, conf *config.Config) error {
pass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
user.Password = string(pass)
for _, database := range conf.Databases {
err := database.Database.AddUser(user)
if err != nil {
return err
}
}
return nil
}
// Login checks the provided username/password combo against the first configured database
func Login(username, password string, db gogios.Database) map[string]interface{} {
user, err := db.GetUser(username)
if err != nil {
var resp = map[string]interface{}{"status": false, "message": "Username not found"}
return resp
}
expiresAt := time.Now().Add(time.Minute * 100000).Unix()
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if err != nil && err == bcrypt.ErrMismatchedHashAndPassword {
var resp = map[string]interface{}{"status": false, "message": "Invalid username and password combo"}
return resp
}
tk := Token{
UserID: user.ID,
Name: user.Name,
StandardClaims: &jwt.StandardClaims{
ExpiresAt: expiresAt,
},
}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
tokenString, err := token.SignedString([]byte("secret"))
if err != nil {
fmt.Println(err)
}
var resp = map[string]interface{}{"status": true, "message": "Authentication success"}
resp["token"] = tokenString
resp["user"] = user
return resp
}