Advertisement
Guest User

Untitled

a guest
Sep 21st, 2021
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 3.71 KB | None | 0 0
  1. package controllers
  2.  
  3. import (
  4.     "CRTProject/models"
  5.     "CRTProject/services"
  6.     "fmt"
  7.     jwt "github.com/appleboy/gin-jwt/v2"
  8.     "github.com/gin-gonic/contrib/sessions"
  9.     "github.com/gin-gonic/gin"
  10.     "github.com/sirupsen/logrus"
  11.     "golang.org/x/crypto/bcrypt"
  12.     "log"
  13.     "time"
  14. )
  15.  
  16. type Router struct {
  17.     Router   *gin.Engine
  18.     Database *services.DatabaseService
  19.  
  20.     UserController UserController
  21. }
  22.  
  23. func (r *Router) Start() {
  24.     r.Router = gin.New()
  25.     r.Router.Use(sessions.Sessions("supersecretsession", sessions.NewCookieStore([]byte("secret"))))
  26.  
  27.     r.Database = &services.DatabaseService{}
  28.     if !r.Database.Boot() {
  29.         return
  30.     }
  31.  
  32.     r.UserController = UserController{r.Database}
  33.     var jwtMiddleware = r.JwtMiddleware()
  34.  
  35.     authGroup := r.Router.Group("/auth")
  36.     authGroup.GET("/refresh_token", jwtMiddleware.LoginHandler)
  37.     authGroup.POST("/login", jwtMiddleware.LoginHandler)
  38.  
  39.     apiGroup := r.Router.Group("/api")
  40.     apiGroup.Use(jwtMiddleware.MiddlewareFunc())
  41.     {
  42.         apiGroup.GET("/users", r.UserController.GetUsers)
  43.         apiGroup.GET("/user", r.UserController.GetUser)
  44.         apiGroup.GET("/test", r.Simple_test)
  45.     }
  46.  
  47.     err := r.Router.Run(":8000")
  48.     if err != nil {
  49.         logrus.Errorf("Can't start backend! Error: %s\n", err.Error())
  50.         return
  51.     }
  52. }
  53.  
  54. func (r *Router) Simple_test(c *gin.Context) {
  55.     claims := jwt.ExtractClaims(c)
  56.     user, _ := c.Get(identityKey)
  57.     c.JSON(200, gin.H{
  58.         identityKey : claims[identityKey],
  59.         "claims_all" : claims,
  60.         "user" : user,
  61.  
  62.     })
  63. }
  64.  
  65. var identityKey = "username"
  66. func (r *Router) JwtMiddleware() *jwt.GinJWTMiddleware {
  67.     m, err := jwt.New(&jwt.GinJWTMiddleware{
  68.         Realm:      "CRT",
  69.         Key:        []byte("supersecretkey"),
  70.         Timeout:    time.Minute * 50, // TODO : change this value
  71.         MaxRefresh: time.Minute * 50, // TODO : change this value
  72.         IdentityKey: identityKey,
  73.         PayloadFunc: func(data interface{}) jwt.MapClaims {
  74.             if v, ok := data.(*models.User); ok {
  75.                 log.Printf("%v", v)
  76.                 return jwt.MapClaims{
  77.                     identityKey: v.Username,
  78.                 }
  79.             }
  80.             return jwt.MapClaims{}
  81.         },
  82.         IdentityHandler: func(c *gin.Context) interface{} {
  83.             claims := jwt.ExtractClaims(c)
  84.             log.Printf("%v", claims)
  85.             log.Printf("%v", claims["IdentityKey"])
  86.             return &models.User{
  87.                 Username: fmt.Sprintf("%v", claims[identityKey]),
  88.             }
  89.         },
  90.         //Authenticator: r.Authenticator,
  91.         Authenticator: func(c *gin.Context) (interface{}, error) {
  92.             var credentials = struct {
  93.                 Login    string `form:"login" json:"login" binding:"required"`
  94.                 Password string `form:"password" json:"password" binding:"required"`
  95.             }{}
  96.  
  97.             if err := c.ShouldBind(&credentials); err != nil {
  98.                 return "", jwt.ErrMissingLoginValues
  99.             }
  100.  
  101.             var userModel models.User
  102.             r.Database.DB.Where(models.User{Login: credentials.Login}).First(&userModel)
  103.             if userModel.ID == 0 {
  104.                 return "", jwt.ErrFailedAuthentication
  105.             }
  106.             err := bcrypt.CompareHashAndPassword([]byte(userModel.Password), []byte(credentials.Password))
  107.             if err != nil {
  108.                 return "", jwt.ErrFailedAuthentication
  109.             }
  110.             return userModel, nil
  111.         },
  112.         Authorizator: func(data interface{}, c *gin.Context) bool {
  113.             if _, ok := data.(*models.User); ok {
  114.                 return true
  115.             }
  116.             return false
  117.         },
  118.         Unauthorized: func(c *gin.Context, code int, message string) {
  119.             c.JSON(code, gin.H{
  120.                 "code":    code,
  121.                 "message": message,
  122.             })
  123.         },
  124.         TokenLookup: "header: Authorization, query: token, cookie: jwt",
  125.         TokenHeadName: "Bearer",
  126.         TimeFunc: time.Now,
  127.     },
  128.     )
  129.  
  130.     if err != nil {
  131.         logrus.Errorf("Can't wake up JWT Middleware! Error: %s\n", err.Error())
  132.         return nil
  133.     }
  134.  
  135.     errInit := m.MiddlewareInit()
  136.     if errInit != nil {
  137.         logrus.Errorf("Can't init JWT Middleware! Error: %s\n", errInit.Error())
  138.         return nil
  139.     }
  140.  
  141.     return m
  142. }
  143.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement