/
auth-controller.go
33 lines (30 loc) · 963 Bytes
/
auth-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
package controllers
import (
"errors"
"github.com/antonioalfa22/go-rest-template/internal/pkg/persistence"
"github.com/antonioalfa22/go-rest-template/pkg/crypto"
"github.com/antonioalfa22/go-rest-template/pkg/http-err"
"github.com/gin-gonic/gin"
"log"
"net/http"
)
type LoginInput struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
func Login(c *gin.Context) {
var loginInput LoginInput
_ = c.BindJSON(&loginInput)
s := persistence.GetUserRepository()
if user, err := s.GetByUsername(loginInput.Username); err != nil {
http_err.NewError(c, http.StatusNotFound, errors.New("user not found"))
log.Println(err)
} else {
if !crypto.ComparePasswords(user.Hash, []byte(loginInput.Password)) {
http_err.NewError(c, http.StatusForbidden, errors.New("user and password not match"))
return
}
token, _ := crypto.CreateToken(user.Username)
c.JSON(http.StatusOK, token)
}
}