Example #1
0
func (h *LoginHandler) Logout(res http.ResponseWriter, req *http.Request) {
	session := repositories.Session(res, req)
	err := session.Clear()

	if err != nil {
		log.Println("Error when clearing session:", err)
	}

	h.RedirectToLogin(res, req)
}
Example #2
0
func (f *LoginForm) createSession() error {
	session := repositories.Session(f.ResponseWriter, f.Request)
	session.SetValue("user_id", f.User.Id)
	err := session.Save()

	if err != nil {
		log.Println("Failed to save session:", err)
		return LoginFailedError
	}

	return nil
}
Example #3
0
func Csrf(res http.ResponseWriter, req *http.Request, chain *RequestFilterChain) {
	session := repositories.Session(res, req)
	sessionToken, ok := session.Value("CsrfToken").(string)

	if ok {
		formToken := req.FormValue("CsrfToken")

		if sessionToken == "" || sessionToken != formToken {
			http.Error(res, "Forbidden", http.StatusForbidden)

			return
		}

		chain.next()
	} else {
		http.Error(res, "Forbidden", http.StatusForbidden)
	}
}
Example #4
0
func getOrCreateCsrfToken(res http.ResponseWriter, req *http.Request) (string, error) {
	session := repositories.Session(res, req)

	token, ok := session.Value("CsrfToken").(string)

	if !ok {
		randomKey := securecookie.GenerateRandomKey(32)
		token = hex.EncodeToString(randomKey)
		session.SetValue("CsrfToken", token)

		err := session.Save()

		if err != nil {
			return "", err
		}
	}

	return token, nil
}
Example #5
0
func (f *Filters) Authenticate(res http.ResponseWriter, req *http.Request, chain *RequestFilterChain) {
	session := repositories.Session(res, req)
	value := session.Value("user_id")

	if id, ok := value.(int); ok {
		user, err := f.Users.FindById(id)

		if err != nil {
			if err != repositories.NotFoundError {
				log.Println("Error when finding user for authentication:", err)
			}

			f.RedirectToLogin(res, req)

			return
		}

		context.SetCurrentUser(req, user)
		chain.next()
	} else {
		f.RedirectToLogin(res, req)
	}
}