waechter

package module
v0.0.0-...-dd0c161 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2017 License: MIT Imports: 8 Imported by: 6

README

Waechter - Logo

Travis CI build status Go Report Card Codecov Card


Go Wächter [German = guard] is a library to implement JWT auth in go apps. It is supposed to bootstrap a web application bringing all necessary features.


Current status

Currently working on the basic functionality. This package is not ready for consumption yet.

Dependencies and Adapters

Wächter does not rely on external services, but it comes with adapters for SMTP and MongoDB. You can also implement your own connections by following the interfaces defined in db-adapter.go and email-adapter.go

Features

  • Administration Notifications
  • Brute-Force Protection
  • Invite System
  • Notification Settings
  • OAuth
  • IP Location check
  • Auth using JWT, Access/Refresh Token architecture
  • Registration
  • Password Recovery
  • Email Verification
  • Adapter based allows to add custom email and database connections
  • Fully internationalized. Allows to translate all messages and emails
  • Comes with beautiful email templates, but you can add your own
  • Configurable access token generation builds the foundation for complex auth needs.

Security

Wäechter uses scrypt to hash passwords using an application secret and a salt unique to every user. It also hashes email activation tokens.

The refresh tokens are saved as JWT to httpOnly cookies (if you're using the gin adapter). This is recommended to prevent XSS!

Getting started

    go get github.com/ElectricCookie/go-waechter
    import(
        "github.com/ElectricCookie/go-waechter"
    )

    func main(){

        // Setup a db adapter

        dbAdapter := NewMongoAdapter("localhost:27017", "waechter-test-db")

        // Setup an SMTP email adapter
        emailAdapter := NewSMTPAdapter("myemailhost",1337,)


        // TODO i18n adapter

        // Application secret is used to hash jwts!
        w := New("some-application-secret", "jwt-issuedby-claim", dbAdapter, emailAdapter)

        // You can now use waechter. To get started quickly you can also use the gin adapter

    }

Documentation

Index

Constants

This section is empty.

Variables

View Source
var EnableThrottle = true

EnableThrottle determines whether there is a check for blocking. This is only used for testing. Disabling throttles in production is NOT recommended!

View Source
var HashExpense = 16384

HashExpense sets the amount of computing power used by scrypt.

Functions

This section is empty.

Types

type AuthError

type AuthError struct {
	ErrorCode   string `json:"errorCode"`
	Description string `json:"description"`
	IsInternal  bool   `json:"isInternal"`
	Err         error
}

AuthError describes all errors that can happen in this package

func CryptError

func CryptError(err error) *AuthError

CryptError occurs if an encryption process fails

func InvalidParametersError

func InvalidParametersError(err error) *AuthError

InvalidParametersError is thrown if the parameters passed to a request are invalid

func NotLoggedInError

func NotLoggedInError() *AuthError

NotLoggedInError obviously.

type DBAdapter

type DBAdapter interface {
	GetUserByEmail(email string) (*User, error)
	GetUserByUsername(username string) (*User, error)
	GetUserByID(id string) (*User, error)

	GetUserByUsernameOrEmail(input string) (*User, error)

	CreateUser(*User) error

	VerifyEmail(userID string) error

	InsertRefreshToken(token *RefreshToken) error

	SetForgotPasswordToken(userID string, token string) error

	SetVerificationToken(userID string, token string) error

	FindRefreshToken(userID string, tokenID string) (*RefreshToken, error)

	SetPassword(userID string, hash string) error
}

DBAdapter is an interface used to connect to a database

type Email

type Email struct {
	From    string
	To      string
	Subject string
	Content string
}

Email wraps a message to be sent to a user

type EmailAdapter

type EmailAdapter interface {
	SendEmail(email *Email) error
}

EmailAdapter is used to send registration emails or request a new password

type LocalesAdapter

type LocalesAdapter interface {
	GetRegistrationEmail(user *User, verificationToken string) (*Email, error)
	GetForgotPasswordEmail(user *User, forgotPasswordToken string) (*Email, error)
	GetPasswordResetEmail(user *User) (*Email, error)
	GetLanguages() []string
	GetDefaultLanguage() string
}

LocalesAdapter describes all localization options in go-waechter

type RefreshToken

type RefreshToken struct {
	Token   string `json:"tokenId" bson:"_id"`
	UserID  string `json:"userId" bson:"userId"`
	Expires int64  `json:"expires" bson:"expires"`
}

RefreshToken is a token that can be used to gain access to an access_token

type User

type User struct {
	ID       string `bson:"_id"`
	Username string `bson:"username"`
	Email    string `bson:"email"`

	FirstName string `bson:"firstName"`
	LastName  string `bson:"lastName"`

	PasswordHash string `bson:"passwordHash"`
	Salt         string `bson:"salt"`

	ForgotPasswordToken       string `bson:"forgotPasswordToken"`
	ForgotPasswordRequestTime int64  `bson:"forgotPasswordTokenRequestTime"`

	Language string `bson:"language"`

	EmailVerfied      bool   `bson:"emailVerified"`
	VerificationToken string `bson:"verificationToken"`

	Registered time.Time `bson:"registeredAt"`
	LastLogin  time.Time `bson:"lastLoginAt"`
}

User is the general user structure

type UserForgotPasswordParams

type UserForgotPasswordParams struct {
	Email string `json:"email" binding:"required" valid:"required,email"`
}

UserForgotPasswordParams describes parameters passed to UserForgotPassword

type UserLoginEmailOrUsernameParams

type UserLoginEmailOrUsernameParams struct {
	UsernameOrEmail string `json:"usernameOrEmail" binding:"required"`
	Password        string `json:"password" binding:"required"`
	RememberMe      bool   `json:"rememberMe"`
}

UserLoginEmailOrUsernameParams is the required information for logging in

type UserLoginEmailParams

type UserLoginEmailParams struct {
	Email      string `json:"email" binding:"required"`
	Password   string `json:"password" binding:"required"`
	RememberMe bool   `json:"rememberMe" binding:"required"`
}

UserLoginEmailParams is the required information for loggin in using the email address

type UserLoginUsernameParams

type UserLoginUsernameParams struct {
	Username   string `json:"username" binding:"required"`
	Password   string `json:"password" binding:"required"`
	RememberMe bool   `json:"rememberMe" binding:"required"`
}

UserLoginUsernameParams is the required infromation for logging in using the username

type UserRegisterParams

type UserRegisterParams struct {
	Username  string `valid:"required" json:"username" binding:"required"`
	Password  string `valid:"required" json:"password" binding:"required"`
	Email     string `valid:"required,email" json:"email" binding:"required"`
	FirstName string `valid:"required" json:"firstName" binding:"required"`
	LastName  string `valid:"required" json:"lastName" binding:"required"`
	Language  string `valid:"required" json:"language" binding:"required"`
}

UserRegisterParams are the parameters used to register a new user.

type UserResetPasswordParams

type UserResetPasswordParams struct {
	UserID      string `json:"userId" bind:"required"`
	Token       string `json:"token" bind:"required"`
	NewPassword string `json:"newPassword" bind:"required"`
}

UserResetPasswordParams describes the data passed to ResetPassword

type UserSendVerficationParams

type UserSendVerficationParams struct {
	Email string `json:"email" validate:"email" binding:"required"`
}

UserSendVerficationParams describes parameters that are required to request a verification

type UserVerifyEmailParams

type UserVerifyEmailParams struct {
	UserID string `json:"userId" binding:"required"`
	Token  string `json:"token" binding:"required"`
}

UserVerifyEmailParams describes the paramteres passed to UserVerifyEmailAddress

type Waechter

type Waechter struct {
	// JWT Information
	JwtSecret string
	JwtIssuer string
	// Email Address of administrator
	AdminEmail string
	// Notifications
	NotificationLogin           bool
	NotificationRegisterd       bool
	NotificationAdminRegistered bool
	// Registration related
	RequireInvite     bool
	RequireActivation bool
	// Login related
	SessionDurationDefault    time.Duration
	SessionDurationRememberMe time.Duration
	// Adapters
	DbAdapter    DBAdapter
	Locales      LocalesAdapter
	EmailAdapter EmailAdapter
}

Waechter wraps a waechter instance

func New

func New(jwtSecret string, jwtIssuer string, dbAdapter DBAdapter, emailAdapter EmailAdapter, translations LocalesAdapter) *Waechter

New creates a new waechter

func (*Waechter) UserCheckAccessToken

func (waechter *Waechter) UserCheckAccessToken(realm string, token string) (*jwt.StandardClaims, *AuthError)

UserCheckAccessToken make sure the access token is valid

func (*Waechter) UserCheckRefreshToken

func (waechter *Waechter) UserCheckRefreshToken(jwtToken string) (*User, *jwt.StandardClaims, error)

UserCheckRefreshToken checks if a refresh token is valid. In case of invalidity a theft is assumed and the users sessions are nuked

func (*Waechter) UserForgotPassword

func (w *Waechter) UserForgotPassword(parameters UserForgotPasswordParams) (string, *AuthError)

UserForgotPassword sends an email to recover the password

func (*Waechter) UserGenerateAccessToken

func (waechter *Waechter) UserGenerateAccessToken(claims *jwt.StandardClaims, realm string, expires time.Duration) (string, *AuthError)

UserGenerateAccessToken issues a new access token based on a refresh token

func (*Waechter) UserGenerateRefreshToken

func (waechter *Waechter) UserGenerateRefreshToken(userID string, expires int64) (string, *AuthError)

UserGenerateRefreshToken generates a new refresh-token and saves it in the database

func (*Waechter) UserLoginEmail

func (waechter *Waechter) UserLoginEmail(parameters UserLoginEmailParams) (string, *AuthError)

UserLoginEmail logs in using emailemail

func (*Waechter) UserLoginUsername

func (waechter *Waechter) UserLoginUsername(parameters UserLoginUsernameParams) (string, *AuthError)

UserLoginUsername logs in using email

func (*Waechter) UserLoginWithUsernameOrEmail

func (waechter *Waechter) UserLoginWithUsernameOrEmail(parameters UserLoginEmailOrUsernameParams) (string, *AuthError)

UserLoginWithUsernameOrEmail logs a user in using email or username and password. Returns a new refresh token.

func (*Waechter) UserRegister

func (waechter *Waechter) UserRegister(params UserRegisterParams) *AuthError

UserRegister a new user

func (*Waechter) UserResetPassword

func (waechter *Waechter) UserResetPassword(params UserResetPasswordParams) *AuthError

UserResetPassword changes the password using a reset token. It also sends an email to notify the user of the changes made to the account

func (*Waechter) UserSendVerificationEmail

func (waechter *Waechter) UserSendVerificationEmail(parameters UserSendVerficationParams) (string, *AuthError)

UserSendVerificationEmail sends an email to the user with a link to verify their email address

func (*Waechter) UserVerifyEmailAddress

func (w *Waechter) UserVerifyEmailAddress(parameters UserVerifyEmailParams) *AuthError

UserVerifyEmailAddress verifies the email address

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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