Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added AuthN, AuthZ and HTTP Basic Auth #1

Merged
merged 3 commits into from
Jun 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package auth

import (
"github.com/jay-dee7/parachute/cache"
"github.com/jay-dee7/parachute/config"
"github.com/labstack/echo/v4"
)

type Authentication interface {
SignUp(ctx echo.Context) error
SignIn(ctx echo.Context) error
BasicAuth(username, password string) (map[string]interface{}, error)
}

type auth struct {
store cache.Store
c *config.RegistryConfig
}

func New(s cache.Store, c *config.RegistryConfig) Authentication {
a := &auth{
store: s,
c: c,
}

return a
}
21 changes: 21 additions & 0 deletions auth/bcrypt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package auth

import "golang.org/x/crypto/bcrypt"

var bcryptMincost = 6

func (a *auth) hashPassword(password string) (string, error) {
// Convert password string to byte slice
var passwordBytes = []byte(password)

// Hash password with Bcrypt's min cost
hashedPasswordBytes, err := bcrypt.GenerateFromPassword(passwordBytes, bcryptMincost)

return string(hashedPasswordBytes), err
}

func (a *auth) verifyPassword(hashedPassword, currPassword string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(currPassword))

return err == nil
}
80 changes: 80 additions & 0 deletions auth/jwt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package auth

import (
"fmt"
"github.com/golang-jwt/jwt"
"time"
)

type Claims struct {
jwt.StandardClaims
Access AccessList
}

func (a *auth) newToken(u User, tokenLife int64) (string, error) {
//for now we're sending same name for sub and name.
//TODO when repositories need collaborators
claims := a.createClaims(u.Username, u.Username, tokenLife)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

// Generate encoded token and send it as response.
t, err := token.SignedString([]byte(a.c.SigningSecret))
if err != nil {
return "", err

}

return t, nil
}

func (a *auth) createClaims(sub, name string, tokenLife int64) Claims {
claims := Claims{
StandardClaims: jwt.StandardClaims{
Audience: "openregistry.dev",
ExpiresAt: tokenLife,
Id: "",
IssuedAt: time.Now().Unix(),
Issuer: "openregistry.dev",
NotBefore: time.Now().Unix(),
Subject: sub,
},
Access: AccessList{
{
Type: "repository",
Name: fmt.Sprintf("%s/*", name),
Actions: []string{"push", "pull"},
},
},
}

return claims
}

type AccessList []struct {
Type string `json:"type"`
Name string `json:"name"`
Actions []string `json:"actions"`
}

/*
claims format
{
"iss": "auth.docker.com",
"sub": "jlhawn",
"aud": "registry.docker.com",
"exp": 1415387315,
"nbf": 1415387015,
"iat": 1415387015,
"jti": "tYJCO1c6cnyy7kAn0c7rKPgbV1H1bFws",
"access": [
{
"type": "repository",
"name": "samalba/my-app",
"actions": [
"pull",
"push"
]
}
]
}
*/
66 changes: 66 additions & 0 deletions auth/signin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package auth

import (
"encoding/json"
"fmt"
"github.com/labstack/echo/v4"
"net/http"
"time"
)

func (a *auth) SignIn(ctx echo.Context) error {
var user User

if err := json.NewDecoder(ctx.Request().Body).Decode(&user); err != nil {
return ctx.JSON(http.StatusBadRequest, echo.Map{
"error": err.Error(),
})
}
if user.Email == "" || user.Password == "" {
return ctx.JSON(http.StatusBadRequest, echo.Map{
"error": "Email/Password cannot be empty",
})
}

if err := verifyEmail(user.Email); err != nil {
return ctx.JSON(http.StatusBadRequest, echo.Map{
"error": err.Error(),
})
}

key := fmt.Sprintf("%s/%s", UserNameSpace, user.Username)
bz, err := a.store.Get([]byte(key))
if err != nil {
return ctx.JSON(http.StatusBadRequest, echo.Map{
"error": err.Error(),
})
}

var userFromDb User
if err := json.Unmarshal(bz, &userFromDb); err != nil {
return ctx.JSON(http.StatusInternalServerError, echo.Map{
"error": err.Error(),
})
}

if !a.verifyPassword(userFromDb.Password, user.Password) {
return ctx.JSON(http.StatusUnauthorized, echo.Map{
"error": "invalid password",
})
}

tokenLife := time.Now().Add(time.Hour * 24 * 14).Unix()
token, err := a.newToken(user, tokenLife)
if err != nil {
return ctx.JSON(http.StatusInternalServerError, echo.Map{
"error": err.Error(),
})
}

return ctx.JSON(http.StatusOK, echo.Map{
"token": token,
"expires_in": tokenLife,
"issued_at": time.Now().Unix(),
})

}
183 changes: 183 additions & 0 deletions auth/signup.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
package auth

import (
"encoding/json"
"fmt"
"github.com/labstack/echo/v4"
"io"
"net/http"
"regexp"
"strings"
"unicode"
)

type User struct {
Id string `json:"id"`
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
}

const UserNameSpace = "users"

func (a *auth) ValidateUser(u User) error {

if err := verifyEmail(u.Email); err != nil {
return err
}
key := fmt.Sprintf("%s/%s", UserNameSpace, u.Email)
_, err := a.store.Get([]byte(key))
if err == nil {
return fmt.Errorf("user already exists, try loggin in or password reset")
}

if len(u.Username) < 3 {
return fmt.Errorf("username should be atleast 3 chars")
}

bz, err := a.store.ListWithPrefix([]byte(UserNameSpace))
if err != nil {
return fmt.Errorf("internal server error")
}

if bz != nil {
var userList []User
fmt.Printf("%s\n", bz)
if err := json.Unmarshal(bz, &userList); err != nil {

if strings.Contains(err.Error(), "object into Go value of type []auth.User") {
var usr User
if e := json.Unmarshal(bz, &usr); e != nil {
return e
}
userList = append(userList, usr)
} else {
return fmt.Errorf("error in unmarshaling: %w", err)
}
}

for _, user := range userList {
if u.Username == user.Username {
return fmt.Errorf("username already taken")
}
}
}
return verifyPassword(u.Password)
}

func verifyEmail(email string) error {
if email == "" {
return fmt.Errorf("email can not be empty")
}
emailReg := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")

if !emailReg.Match([]byte(email)) {
return fmt.Errorf("email format invalid")
}

return nil
}

func verifyPassword(password string) error {
var uppercasePresent bool
var lowercasePresent bool
var numberPresent bool
var specialCharPresent bool
const minPassLength = 8
const maxPassLength = 64
var passLen int
var errorString string

for _, ch := range password {
switch {
case unicode.IsNumber(ch):
numberPresent = true
passLen++
case unicode.IsUpper(ch):
uppercasePresent = true
passLen++
case unicode.IsLower(ch):
lowercasePresent = true
passLen++
case unicode.IsPunct(ch) || unicode.IsSymbol(ch):
specialCharPresent = true
passLen++
case ch == ' ':
passLen++
}
}
appendError := func(err string) {
if len(strings.TrimSpace(errorString)) != 0 {
errorString += ", " + err
} else {
errorString = err
}
}
if !lowercasePresent {
appendError("lowercase letter missing")
}
if !uppercasePresent {
appendError("uppercase letter missing")
}
if !numberPresent {
appendError("atleast one numeric character required")
}
if !specialCharPresent {
appendError("special character missing")
}
if !(minPassLength <= passLen && passLen <= maxPassLength) {
appendError(fmt.Sprintf("password length must be between %d to %d characters long", minPassLength, maxPassLength))
}

if len(errorString) != 0 {
return fmt.Errorf(errorString)
}
return nil
}

func (a *auth) SignUp(ctx echo.Context) error {

var u User
bz, err := io.ReadAll(ctx.Request().Body)
if err != nil {
return ctx.JSON(http.StatusBadRequest, echo.Map{
"error": err.Error(),
"msg": "invalid request body",
})
}
ctx.Request().Body.Close()

if err := json.Unmarshal(bz, &u); err != nil {
return ctx.JSON(http.StatusBadRequest, echo.Map{
"error": err.Error(),
"msg": "couldn't marshal user",
})
}

if err := a.ValidateUser(u); err != nil {
return ctx.JSON(http.StatusBadRequest, echo.Map{
"error": err.Error(),
"msg": "bananas",
})
}

hpwd, err := a.hashPassword(u.Password)
if err != nil {
return ctx.JSON(http.StatusInternalServerError, echo.Map{
"error": err.Error(),
})
}
u.Password = hpwd
bz, _ = json.Marshal(u)

key := fmt.Sprintf("%s/%s", UserNameSpace, u.Username)
if err := a.store.Set([]byte(key), bz); err != nil {
return ctx.JSON(http.StatusInternalServerError, echo.Map{
"error": err.Error(),
})
}

return ctx.JSON(http.StatusCreated, echo.Map{
"message": "user successfully created",
})
}
Loading