/
login_controller.go
93 lines (82 loc) · 2.3 KB
/
login_controller.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package controllers
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gin-gonic/gin"
"github.com/tapfunds/tf/auth/api/auth"
"github.com/tapfunds/tf/auth/api/models"
"github.com/tapfunds/tf/auth/api/security"
"github.com/tapfunds/tf/auth/api/utils/formaterror"
"golang.org/x/crypto/bcrypt"
)
func (server *Server) Login(c *gin.Context) {
//clear previous error if any
errList = map[string]string{}
body, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{
"status": http.StatusUnprocessableEntity,
"first error": "Unable to get request",
})
return
}
user := models.User{}
err = json.Unmarshal(body, &user)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{
"status": http.StatusUnprocessableEntity,
"error": "Cannot unmarshal body",
})
return
}
user.Prepare()
errorMessages := user.Validate("login")
if len(errorMessages) > 0 {
c.JSON(http.StatusUnprocessableEntity, gin.H{
"status": http.StatusUnprocessableEntity,
"error": errorMessages,
})
return
}
userData, err := server.SignIn(user.Email, user.Password)
if err != nil {
formattedError := formaterror.FormatError(err.Error())
c.JSON(http.StatusUnprocessableEntity, gin.H{
"status": http.StatusUnprocessableEntity,
"error": formattedError,
})
return
}
c.JSON(http.StatusOK, gin.H{
"status": http.StatusOK,
"response": userData,
})
}
func (server *Server) SignIn(email, password string) (map[string]interface{}, error) {
var err error
userData := make(map[string]interface{})
user := models.User{}
err = server.DB.Debug().Model(models.User{}).Where("email = ?", email).Take(&user).Error
if err != nil {
fmt.Println("this is the error getting the user: ", err)
return nil, err
}
err = security.VerifyPassword(user.Password, password)
if err != nil && err == bcrypt.ErrMismatchedHashAndPassword {
fmt.Println("this is the error hashing the password: ", err)
return nil, err
}
token, err := auth.CreateToken(user.ID)
if err != nil {
fmt.Println("this is the error creating the token: ", err)
return nil, err
}
userData["token"] = token
userData["id"] = user.ID
userData["email"] = user.Email
userData["avatar_path"] = user.AvatarPath
userData["username"] = user.Username
return userData, nil
}