generated from shoriwe/base-go-repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
67 lines (61 loc) · 1.4 KB
/
auth.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
package models
import (
"errors"
"github.com/golang-jwt/jwt/v5"
"github.com/hidromatologia-v2/models/tables"
"gorm.io/gorm"
)
func (c *Controller) Authenticate(u *tables.User) (*tables.User, error) {
user := new(tables.User)
err := c.DB.
Where("username = ?", u.Username).
First(user).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUnauthorized
}
return nil, err
}
if !user.Authenticate(u.Password) {
return nil, ErrUnauthorized
}
return user, nil
}
func (c *Controller) Register(u *tables.User) error {
return c.DB.Create(u).Error
}
func (c *Controller) Authorize(jwtS string) (*tables.User, error) {
token, pErr := jwt.Parse(jwtS, c.JWT.KeyFunc)
if pErr != nil {
return nil, pErr
}
var fUser tables.User
fErr := fUser.FromClaims(token.Claims.(jwt.MapClaims))
if fErr != nil {
return nil, fErr
}
user := new(tables.User)
err := c.DB.
Where("uuid = ?", fUser.UUID).
First(user).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUnauthorized
}
return nil, err
}
return user, nil
}
func (c *Controller) AuthorizeAPIKey(apiKey string) (*tables.Station, error) {
station := new(tables.Station)
err := c.DB.
Where("api_key = ?", apiKey).
First(station).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUnauthorized
}
return nil, err
}
return station, nil
}