func Server() { runtime.GOMAXPROCS(runtime.NumCPU()) if _, err := database.InitDb(); err != nil { panic(err) } app := gin.New() app.Use(func(c *gin.Context) { c.Set(config.SecretKey, config.GetSecret()) c.Next() }) if config.GetEnv() != config.EnvProduction { app.Use(gin.Logger()) app.Use(gin.Recovery()) } else { app.Use(middleware.Recovery()) } app.Use(middleware.ErrorHandler()) app.Static("/public", "./public") //Set up api v1 setupApiV1(app) env := config.GetEnvValue() app.Run(env.Server.Host + ":" + strconv.Itoa(env.Server.Port)) }
/** TODO: - Get email and password from post request - Find user **/ func (a *authController) Login(c *gin.Context) { var userLogin models.UserLogin if err := c.Bind(&userLogin); err != nil { panic(err) } user, err := authResource.Login(userLogin.Email, userLogin.Password) if err != nil { c.Error(err) return } token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256")) // Set some claims token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix() // Sign and get the complete encoded token as a string apiKey, err := token.SignedString([]byte(config.GetSecret())) if err != nil { c.Error(apiErrors.ThrowError(apiErrors.ServerError)) return } // Remove password user.Password = "" c.JSON(200, gin.H{ "user": user, "api-key": apiKey, }) }
/** TODO: - Check user is login - If not return not login error - If logined set "user" in context **/ func (a *authMiddleware) RequireLogin() gin.HandlerFunc { return func(c *gin.Context) { user, err := jwt_lib.ParseFromRequest(c.Request, func(token *jwt_lib.Token) (interface{}, error) { b := ([]byte(config.GetSecret())) return b, nil }) if err != nil { c.Error(apiErrors.ThrowError(apiErrors.UserNotLogined)) return } c.Set("user", user) } }