auth

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 15, 2021 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var GenerateJWT = func(userID, secret string, expiresIn int) (string, error) {
	claims := jwt.MapClaims{}
	claims["authorized"] = true
	claims["sub"] = userID
	claims["iat"] = time.Now().Unix()
	if expiresIn != 0 {
		claims["exp"] = time.Now().Add(time.Minute * time.Duration(expiresIn)).Unix()
	}

	at := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return at.SignedString([]byte(secret))
}

GenerateJWT creates a JWT with custom

View Source
var VerifyJWT = func(token, secret string) (string, error) {

	jwtToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {

		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(secret), nil
	})
	if err != nil {
		return "", err
	}

	claims, ok := jwtToken.Claims.(jwt.MapClaims)
	if ok && jwtToken.Valid {
		userID, ok := claims["sub"].(string)
		if !ok {
			return "", errors.New("Failed to verify JWT and extract the subject")
		}

		return userID, nil
	}

	return "", errors.New("Failed to verify JWT and extract the subject")
}

VerifyJWT checks that the JWT is well formed (i.e. it can be parsed) and returns the user ID encoded in the JWT.

Functions

func GetTokenFromRequest

func GetTokenFromRequest(r *http.Request) string

GetTokenFromRequest extracts the token from an HTTP request

func WriteErrorResponse

func WriteErrorResponse(w http.ResponseWriter, statusCode int, err error)

WriteErrorResponse is a helper function that returns JSON response for errors

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client has all the handlers for user related activities

func NewClient

func NewClient(chatroomDB *models.ChatroomDB, jwtSecret string, logger *log.Entry) *Client

NewClient instantiates a new auth client

func (*Client) CreateUser

func (c *Client) CreateUser(w http.ResponseWriter, r *http.Request)

CreateUser is a handler that creates a new user

func (*Client) IsAuthenticated

func (c *Client) IsAuthenticated(next http.Handler) http.Handler

IsAuthenticated is a middleware that checks if a requester is authenticated or not

func (*Client) Login

func (c *Client) Login(w http.ResponseWriter, r *http.Request)

Login validates a user, returning a JWT if login was successful

type CreateUserResponse

type CreateUserResponse struct {
	Username string `json:"username"`
	Email    string `json:"email"`
}

CreateUserResponse is the payload for a successful created user We don't want to send password details in the response

type LoginPayload

type LoginPayload struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

LoginPayload is the payload for a login request

type LoginResponse

type LoginResponse struct {
	Token string `json:"token"`
}

LoginResponse is the payload for a successful login response

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL