-
Notifications
You must be signed in to change notification settings - Fork 0
/
signin.go
66 lines (53 loc) · 1.39 KB
/
signin.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
package auth
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/Gr1N/pacman/models"
"github.com/Gr1N/pacman/modules/oauth2"
)
type signInCompleteBinding struct {
State string `form:"state" binding:"required,len=32"`
Code string `form:"code" binding:"required,len=20"`
}
// SignIn starts authentication process.
func SignIn(c *gin.Context) {
service := c.Param("service")
if err := oauth2.HandleService(service); err != nil {
c.JSON(http.StatusBadRequest, gin.H{})
return
}
redirectURL := oauth2.HandleAuthorizeRequest(service)
c.JSON(http.StatusOK, gin.H{
"redirectURL": redirectURL,
})
}
// SignInComplete finishes authentication process.
func SignInComplete(c *gin.Context) {
service := c.Param("service")
if err := oauth2.HandleService(service); err != nil {
c.JSON(http.StatusBadRequest, gin.H{})
return
}
var b signInCompleteBinding
if err := c.Bind(&b); err != nil {
c.JSON(http.StatusBadRequest, gin.H{})
return
}
if err := oauth2.ValidateAuthorizeRequest(service, b.State); err != nil {
c.JSON(http.StatusBadRequest, gin.H{})
return
}
user, err := oauth2.FinishAuthorizeRequest(service, b.Code)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{})
return
}
token, _ := models.CreateUserToken(user.ID, "Auth "+time.Now().String())
c.JSON(http.StatusOK, gin.H{
"user": gin.H{
"id": user.ID,
"token": token.Value,
},
})
}