-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthHandler.go
More file actions
102 lines (93 loc) · 2.26 KB
/
authHandler.go
File metadata and controls
102 lines (93 loc) · 2.26 KB
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
94
95
96
97
98
99
100
101
102
package handlers
import (
"net/http"
"github.com/Arjuna-Ragil/Localbase/Internal/core/services"
"github.com/gin-gonic/gin"
)
type AuthHandler struct {
Service *services.AuthService
}
type InviteInput struct {
Email string `json:"email"`
Role string `json:"role"`
}
func NewAuthHandler(service *services.AuthService) *AuthHandler {
return &AuthHandler{Service: service}
}
func (ah *AuthHandler) RegisterHandler(c *gin.Context) {
var input services.RegisterInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid Input",
"data": err.Error(),
})
return
}
if err := ah.Service.RegisterService(&input); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "Register service failed",
"data": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "Register service success",
"data": nil,
})
}
func (ah *AuthHandler) LoginHandler(c *gin.Context) {
var input services.LoginInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid Input",
"data": err.Error(),
})
return
}
tokenString, err := ah.Service.LoginService(&input)
if err != nil {
c.JSON(401, gin.H{
"message": "Login failed",
"data": err.Error(),
})
return
}
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie("authorization", tokenString, 3600*24, "/", "", false, true)
c.JSON(http.StatusOK, gin.H{
"message": "Login success",
"data": tokenString,
})
}
func (ah *AuthHandler) LogoutHandler(c *gin.Context) {
c.SetCookie("authorization", "", -1, "/", "", false, true)
c.JSON(http.StatusOK, gin.H{
"message": "Logout success",
"data": nil,
})
}
func (ah *AuthHandler) CreateInviteHandler(c *gin.Context) {
var req InviteInput
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{
"message": "Invalid Input",
"data": err.Error(),
})
return
}
if req.Role == "" {
req.Role = "user"
}
link, err := ah.Service.GenerateInviteService(req.Email, req.Role)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "Invite service failed",
"data": err.Error(),
})
return
}
c.JSON(200, gin.H{
"message": "Invite service success",
"data": link,
})
}