/
authController.go
58 lines (48 loc) 路 1.74 KB
/
authController.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
package rest
import (
"fmt"
"github.com/mmirzaee/userist/models"
"net/http"
)
func postAuthLogin(w http.ResponseWriter, r *http.Request, _ AuthorizedUser, _ int) {
username := r.FormValue("username")
password := r.FormValue("password")
if username == "" || password == "" {
jsonHttpRespond(w, nil, "invalid inputs", http.StatusForbidden)
return
}
user, err := models.GetUserByUsername(username)
if err != nil {
jsonHttpRespond(w, nil, "username not found", http.StatusNotFound)
return
}
isValidPassword := checkPasswordHash(password, user.Password)
if !isValidPassword {
jsonHttpRespond(w, nil, "username or password is wrong", http.StatusForbidden)
return
}
var roles = models.GetUserTenantsPermissions(user.UserTenantRoles)
token := generateToken(TokenData{UserId: user.ID, Roles: roles})
userSafeData := user.Safe()
userSafeData["Token"] = token
userSafeData["Tenants"] = models.GetUserTenants(user.ID)
jsonHttpRespond(w, userSafeData, "", http.StatusOK)
}
func postRefreshToken(w http.ResponseWriter, r *http.Request, user AuthorizedUser, _ int) {
fmt.Println(user)
refreshUser, err := models.GetUserByID(user.User.ID)
if err != nil {
jsonHttpRespond(w, nil, "username not found", http.StatusNotFound)
return
}
var roles = models.GetUserTenantsPermissions(refreshUser.UserTenantRoles)
token := generateToken(TokenData{UserId: refreshUser.ID, Roles: roles})
userSafeData := refreshUser.Safe()
userSafeData["Token"] = token
userSafeData["Tenants"] = models.GetUserTenants(refreshUser.ID)
jsonHttpRespond(w, userSafeData, "", http.StatusOK)
}
func postAuthCheckToken(w http.ResponseWriter, r *http.Request, user AuthorizedUser, _ int) {
u, _ := models.GetUserByID(user.User.ID)
jsonHttpRespond(w, u.Safe(), "", http.StatusOK)
}