示例#1
0
func postLogin(c *gin.Context) {
	// Temporary storage
	credentials := map[string]string{
		"dolanor": "test",
		"tanguy":  "pass",
	}

	var form Login

	if c.Bind(&form) != nil {
		return
	}

	if password, ok := credentials[form.Username]; ok && password == form.Password {
		// generate the jwt
		token := jwt.New(jwt.GetSigningMethod("HS256"))
		token.Claims["name"] = form.Username
		token.Claims["exp"] = time.Now().Add(1 * time.Minute).Unix()
		token.Claims["auth"] = true

		// sign the token
		tokenString, err := token.SignedString([]byte(helper.SymmetricKey))
		if err != nil {
			helper.GenResponse(c, http.StatusBadRequest, "login_form.tmpl", gin.H{"title": "Log in"})
		}

		// save the tokenstring in the cookiestore (maybe use localstorage?)
		session := sessions.Default(c)
		session.Set("token", tokenString)
		session.Save()

		helper.GenResponse(c, http.StatusOK, "login_form.tmpl", gin.H{"title": "Log in", "data": form.Username, "username": form.Username})
	} else {
		helper.GenResponse(c, http.StatusUnauthorized, "login_form.tmpl", gin.H{"title": "Log in"})
	}
}
示例#2
0
func displayProfile(c *gin.Context) {
	data, err := helper.QueryDataService(c)
	if err != nil {
		switch e := err.(type) {
		case *jwt.ValidationError:
			if e.Errors&jwt.ValidationErrorExpired == jwt.ValidationErrorExpired {
				helper.GenResponse(c, http.StatusUnauthorized, "profile.tmpl", gin.H{"title": "Profile", "data": nil})
				return
			}
		case error:
			switch err {
			case api.ErrUnauthorized:
				helper.GenResponse(c, http.StatusUnauthorized, "profile.tmpl", gin.H{"title": "Profile", "data": nil})
				return
			case api.ErrConnectingEndpoint:
				helper.GenResponse(c, http.StatusServiceUnavailable, "profile.tmpl", gin.H{"title": "Profile", "data": nil})
				return
			case api.ErrDataNotFound:
				helper.GenResponse(c, http.StatusNotFound, "profile.tmpl", gin.H{"title": "Profile", "data": nil})
				return
			default:
				helper.GenResponse(c, http.StatusInternalServerError, "profile.tmpl", gin.H{"title": "Profile", "data": nil})
				return
			}
		default:
			helper.GenResponse(c, http.StatusInternalServerError, "profile.tmpl", gin.H{"title": "Profile", "data": nil})
			return
		}
	}

	var profile api.User
	err = json.Unmarshal(data, &profile)
	if err != nil {
		helper.GenResponse(c, http.StatusBadRequest, "profile.tmpl", gin.H{"title": "Profile", "data": nil})
		return
	}

	// If we're here, we can get these informations already without errors
	token, _ := helper.GetTokenFromContext(c)
	username, _ := helper.GetUsernameFromToken(token)
	helper.GenResponse(c, http.StatusOK, "profile.tmpl", gin.H{"title": "Profile", "data": profile, "username": username})
}