Passed
Push — main ( 26be31...19cade )
by Yume
01:25
created

controllers.CheckAuth   B

Complexity

Conditions 5

Size

Total Lines 40
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 26
nop 2
dl 0
loc 40
rs 8.7893
c 0
b 0
f 0
1
package controllers
2
3
import (
4
	"memnixrest/app/database"
5
	"memnixrest/app/models"
6
	"strconv"
7
	"time"
8
9
	"github.com/gofiber/fiber/v2"
10
	"github.com/golang-jwt/jwt"
11
	"golang.org/x/crypto/bcrypt"
12
)
13
14
const SecretKey = "secret"
15
16
func Register(c *fiber.Ctx) error {
17
	var data map[string]string
18
	db := database.DBConn // DB Conn
19
20
	if err := c.BodyParser(&data); err != nil {
21
		return err
22
	}
23
24
	password, _ := bcrypt.GenerateFromPassword([]byte(data["password"]), 14)
25
	user := models.User{
26
		Username: data["username"],
27
		Email:    data["email"],
28
		Password: password,
29
	}
30
31
	db.Create(&user)
32
33
	return c.JSON(user)
34
}
35
36
func Login(c *fiber.Ctx) error {
37
	var data map[string]string
38
	db := database.DBConn // DB Conn
39
40
	if err := c.BodyParser(&data); err != nil {
41
		return err
42
	}
43
44
	var user models.User
45
46
	db.Where("email = ?", data["email"]).First(&user)
47
48
	// handle error
49
	if user.ID == 0 { //default Id when return nil
50
		c.Status(fiber.StatusNotFound)
51
		return c.JSON(fiber.Map{
52
			"message": "User not found!",
53
		})
54
	}
55
56
	// match password
57
	if err := bcrypt.CompareHashAndPassword(user.Password, []byte(data["password"])); err != nil {
58
		c.Status(fiber.StatusBadRequest)
59
		return c.JSON(fiber.Map{
60
			"message": "incorrect password!",
61
		})
62
	}
63
64
	claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{
65
		Issuer:    strconv.Itoa(int(user.ID)),
66
		ExpiresAt: time.Now().Add(time.Hour * 24).Unix(), //1 day
67
	})
68
69
	token, err := claims.SignedString([]byte(SecretKey))
70
	if err != nil {
71
		c.Status(fiber.StatusInternalServerError)
72
		return c.JSON(fiber.Map{
73
			"message": "error when logging in !",
74
		})
75
	}
76
77
	cookie := fiber.Cookie{
78
		Name:     "memnix-jwt",
79
		Value:    token,
80
		Expires:  time.Now().Add(time.Hour * 24),
81
		HTTPOnly: true,
82
	}
83
	c.Cookie(&cookie)
84
85
	return c.JSON(fiber.Map{
86
		"message": "Login Succeeded",
87
		//"token": token,
88
	})
89
}
90
91
func User(c *fiber.Ctx) error {
92
	cookie := c.Cookies("memnix-jwt")
93
	db := database.DBConn // DB Conn
94
95
	token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
96
		return []byte(SecretKey), nil
97
	})
98
99
	if err != nil {
100
		c.Status(fiber.StatusUnauthorized)
101
		return c.JSON(fiber.Map{
102
			"message": "Unauthenticated",
103
		})
104
	}
105
106
	claims := token.Claims.(*jwt.StandardClaims)
107
108
	var user models.User
109
110
	db.Where("id = ?", claims.Issuer).First(&user)
111
112
	return c.JSON(user)
113
}
114
115
func CheckAuth(c *fiber.Ctx, p models.Permission) models.ResponseAuth {
116
	cookie := c.Cookies("memnix-jwt")
117
	db := database.DBConn // DB Conn
118
	token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
119
		return []byte(SecretKey), nil
120
	})
121
122
	if err != nil {
123
		c.Status(fiber.StatusUnauthorized)
124
125
		return models.ResponseAuth{
126
			Message: "Unauthentified",
127
			Success: false,
128
		}
129
	}
130
131
	claims := token.Claims.(*jwt.StandardClaims)
132
133
	var user models.User
134
135
	if res := db.Where("id = ?", claims.Issuer).First(&user); res.Error != nil {
136
		c.Status(fiber.StatusInternalServerError)
137
		return models.ResponseAuth{
138
			Success: false,
139
			Message: "Failed to get the user. Try to logout/login. Otherwise, contact the support",
140
		}
141
	}
142
143
	if user.Permissions < p {
144
		c.Status(fiber.StatusUnauthorized)
145
		return models.ResponseAuth{
146
			Success: false,
147
			Message: "You don't have the right permissions to perform this request.",
148
		}
149
	}
150
151
	return models.ResponseAuth{
152
		Success: true,
153
		Message: "Authentified",
154
		User:    user,
155
	}
156
}
157
158
func Logout(c *fiber.Ctx) error {
159
	cookie := fiber.Cookie{
160
		Name:     "memnix-jwt",
161
		Value:    "",
162
		Expires:  time.Now().Add(-time.Hour),
163
		HTTPOnly: true,
164
	}
165
	c.Cookie(&cookie)
166
167
	return c.JSON(fiber.Map{
168
		"message": "successfully logged out !",
169
	})
170
}
171