auth package

This commit is contained in:
Nazar Kanaev 2021-03-16 21:59:56 +00:00
parent 1a490a8e7a
commit 0d49377879
2 changed files with 16 additions and 14 deletions

View File

@ -1,4 +1,4 @@
package server
package auth
import (
"crypto/hmac"
@ -10,23 +10,24 @@ import (
"time"
)
func userIsAuthenticated(req *http.Request, username, password string) bool {
func IsAuthenticated(req *http.Request, username, password string) bool {
cookie, _ := req.Cookie("auth")
if cookie == nil {
return false
}
parts := strings.Split(cookie.Value, ":")
if len(parts) != 2 || !stringsEqual(parts[0], username) {
if len(parts) != 2 || !StringsEqual(parts[0], username) {
return false
}
return stringsEqual(parts[1], secret(username, password))
return StringsEqual(parts[1], secret(username, password))
}
func userAuthenticate(rw http.ResponseWriter, username, password string) {
func Authenticate(rw http.ResponseWriter, username, password, basepath string) {
expires := time.Now().Add(time.Hour * 24 * 7) // 1 week
var cookiePath string
if BasePath != "" {
cookiePath = BasePath
if basepath != "" {
cookiePath = basepath
} else {
cookiePath = "/"
}
@ -39,7 +40,7 @@ func userAuthenticate(rw http.ResponseWriter, username, password string) {
http.SetCookie(rw, &cookie)
}
func userLogout(rw http.ResponseWriter) {
func Logout(rw http.ResponseWriter) {
cookie := http.Cookie{
Name: "auth",
Value: "",
@ -48,7 +49,7 @@ func userLogout(rw http.ResponseWriter) {
http.SetCookie(rw, &cookie)
}
func stringsEqual(p1, p2 string) bool {
func StringsEqual(p1, p2 string) bool {
return subtle.ConstantTimeCompare([]byte(p1), []byte(p2)) == 1
}

View File

@ -3,9 +3,10 @@ package server
import (
"encoding/json"
"fmt"
"github.com/nkanaev/yarr/src/storage"
"github.com/nkanaev/yarr/src/assets"
"github.com/nkanaev/yarr/src/auth"
"github.com/nkanaev/yarr/src/router"
"github.com/nkanaev/yarr/src/storage"
"html"
"io/ioutil"
"log"
@ -43,12 +44,12 @@ func (s *Server) handler() http.Handler {
}
func (s *Server) handleIndex(c *router.Context) {
if s.requiresAuth() && !userIsAuthenticated(c.Req, s.Username, s.Password) {
if s.requiresAuth() && !auth.IsAuthenticated(c.Req, s.Username, s.Password) {
if c.Req.Method == "POST" {
username := c.Req.FormValue("username")
password := c.Req.FormValue("password")
if stringsEqual(username, s.Username) && stringsEqual(password, s.Password) {
userAuthenticate(c.Out, username, password)
if auth.StringsEqual(username, s.Username) && auth.StringsEqual(password, s.Password) {
auth.Authenticate(c.Out, username, password, BasePath)
http.Redirect(c.Out, c.Req, c.Req.URL.Path, http.StatusFound)
return
}
@ -433,6 +434,6 @@ func (s *Server) handlePageCrawl(c *router.Context) {
}
func (s *Server) handleLogout(c *router.Context) {
userLogout(c.Out)
auth.Logout(c.Out)
c.Out.WriteHeader(http.StatusNoContent)
}