ngauth

package module
v0.91.5 Latest Latest
Warning

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

Go to latest
Published: May 11, 2020 License: MIT Imports: 27 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ngauth

Documentation

Index

Constants

View Source
const (
	LanguageEN = "en"
	LanguageSW = "sw"
	LanguageTR = "tr"
)

Language codes

View Source
const (
	//external errors, eg db, server etc
	ErrorInternalServerError = 1001
	ErrorBadRequest          = 1002
	ErrorDBError             = 1003
	ErrorBackendServerError  = 1004
	ErrorNotAuthorized       = 1005

	//API errors
	ErrorNotFound                       = 2001
	ErrorEmptyFields                    = 2002
	ErrorPasswordsDoNotMatch            = 2003
	ErrorUsernameExists                 = 2004
	ErrorIncorrectUsernameOrPassword    = 2005
	ErrorIncorrectPhoneNumberOrPassword = 2006
	ErrorIncorrectEmailOrPassword       = 2007
	ErrorMissingFunctionParams          = 2008

	//API errors - validations
	ErrorInvalidEmail       = 2009
	ErrorInvalidPhoneNumber = 2010
	ErrorInvalidCountryCode = 2011
	ErrorInvalidOTPCode     = 2012
	ErrorExpiredOTPCode     = 2013

	ErrorAlreadyVerified  = 2014
	ErrorInvalidToken     = 2015
	ErrorGetVerifiedFirst = 2016
	ErrorWrongValueFor    = 2017
	ErrorUserNotFound     = 2018
	ErrorWaitFor          = 2019
)

API Error codes

Variables

This section is empty.

Functions

func ArrayContains

func ArrayContains(lookup string, arr []string) bool

ArrayContains - checks if an array contains a string

func AsyncSendVerifCode

func AsyncSendVerifCode(toEmail string, code string)

AsyncSendVerifCode - sends verification code in a goroutine

func BcryptHashCheck

func BcryptHashCheck(hashedPwd string, plainPwd string) bool

BcryptHashCheck - bcrypt compare hashed and plain passwords

func BcryptHashMake

func BcryptHashMake(pwd string) string

BcryptHashMake - create hashed password

func ErrorResponse

func ErrorResponse(w http.ResponseWriter, message string, apiErrCode int)

ErrorResponse - writes API error response with http status 200 OK, the actual api error code is written in the json body

func ErrorText

func ErrorText(lang string, errCode int) string

ErrorText - returns a text for the API error code. It returns the empty string if the errCode is unknown.

func ExpireAtTime

func ExpireAtTime(tm time.Duration) time.Time

ExpireAtTime returns time.Time expire_at given a time duration

func ExpireAtUTC

func ExpireAtUTC(tm time.Duration) int64

ExpireAtUTC returns unix timestamp expire_at given a time duration

func GenerateUUID

func GenerateUUID() string

GenerateUUID - generate uuid

func GetBoolOrFalse added in v0.91.2

func GetBoolOrFalse(val interface{}) bool

GetBoolOrFalse - get bool or false to be used in post body submissions, be sure val is a float64

func GetFloat64OrZero added in v0.90.7

func GetFloat64OrZero(val interface{}) float64

GetFloat64OrZero - get float64 or zero to be used in post body submissions, be sure val is a float64

func GetInt64OrZero

func GetInt64OrZero(val interface{}) int64

GetInt64OrZero - get int64 or zero to be used in post body submissions, be sure val is a int64

func GetNullableBool added in v0.90.7

func GetNullableBool(val interface{}) null.Bool

GetNullableBool - get a nullable bool

func GetNullableFloat added in v0.90.7

func GetNullableFloat(val interface{}) null.Float

GetNullableFloat - get a nullable float

func GetNullableInt added in v0.90.7

func GetNullableInt(val interface{}) null.Int

GetNullableInt - get a nullable int

func GetNullableString added in v0.90.7

func GetNullableString(val interface{}) null.String

GetNullableString - get a nullable string

func GetNullableTime added in v0.91.2

func GetNullableTime(val interface{}) null.Time

GetNullableTime - get a nullable time

func GetStringOrEmpty

func GetStringOrEmpty(val interface{}) string

GetStringOrEmpty - get string or empty to be used in post body submissions, be sure val is a string

func GetTokenFromHeader

func GetTokenFromHeader(r *http.Request) string

GetTokenFromHeader - gets access_token from header

func HTTPErrorResponse

func HTTPErrorResponse(w http.ResponseWriter, message string, code int)

HTTPErrorResponse - writes an error response with correct http headers ie status, content type etc

func IsEmptyString

func IsEmptyString(s string) bool

IsEmptyString - checks if string is empty or not, no trimming of whitespace for whitespace trimming use IsEmptyTextContent instead

func IsEmptyTextContent

func IsEmptyTextContent(s string) bool

IsEmptyTextContent - checks whether string is empty or contains only whitespace

func IsValidEmail

func IsValidEmail(email string) bool

IsValidEmail - check whether email is valid or not

func LangFromContext

func LangFromContext(ctx context.Context) string

LangFromContext - get lang from context

func LanguageDetector

func LanguageDetector(next http.Handler) http.Handler

LanguageDetector - checks language from cookie,url query and sets it in context

func LogError

func LogError(v ...interface{})

LogError - logs a message to stderr

func LogErrorf added in v0.90.7

func LogErrorf(format string, v ...interface{})

LogErrorf - logs a message to stderr

func LogInfo

func LogInfo(v ...interface{})

LogInfo - logs a message to stdout

func LogInfof added in v0.90.7

func LogInfof(format string, v ...interface{})

LogInfof - logs a message to stdout

func MethodNotAllowedErrorHandler

func MethodNotAllowedErrorHandler(w http.ResponseWriter, r *http.Request)

MethodNotAllowedErrorHandler - Handler for method not allowed error

func NotFoundErrorHandler

func NotFoundErrorHandler(w http.ResponseWriter, r *http.Request)

NotFoundErrorHandler - Handler for not found error

func NowTimestamp

func NowTimestamp() int64

NowTimestamp returns a unix timestamp

func ParseConfig

func ParseConfig(inConfig *Configuration)

ParseConfig parses environment variables to configuration

func SecureRandomNumericString

func SecureRandomNumericString(max int) string

SecureRandomNumericString - generates a random numeric code

func SecureRandomNumericStringStandard

func SecureRandomNumericStringStandard() string

SecureRandomNumericStringStandard - generates random numeric code of length 6

func SendEmail

func SendEmail(toEmail string, subject string, body string) error

SendEmail - sends emails

func SetConfig

func SetConfig(inConfig *Configuration)

SetConfig - set Config for the package

func TimeNow

func TimeNow() time.Time

TimeNow returns time now

Types

type Configuration

type Configuration struct {
	//Port to listen to
	Port string

	//DBConnectionString - Connection String to database
	DBConnectionString string

	//DBDriver for database/sql,eg values mysql,postgres,mssql,sqlite3
	DBDriver           string
	DBPoolMaxIdleConns int
	DBPoolMaxOpenConns int

	UsersTableName    string
	OTPTableName      string
	SessionsTableName string

	//smtp
	SMTPHost     string
	SMTPPort     string
	SMTPUsername string
	SMTPPassword string
	SMTPFrom     string

	//SignKey for generating JWT Tokens
	SignKey              []byte
	JWTAccessExpireMins  int
	JWTRefreshExpireMins int

	//otp
	OTPExpireTime int64
	OTPBanTime    int64
	OTPFindTime   int64
	OTPMaxRetry   int

	//only register verified users
	VerifyBeforeRegister bool

	//proxy
	UpstreamPublicURL  string
	UpstreamPrivateURL string
}

Configuration holds configuration variables

var Config *Configuration

Config holds configuration variables

type Database

type Database interface {
	Init(config *Configuration) error
	Close() error

	//GetUser(userID interface{}, lang string) (*User, *Error)
	GetUserBy(email string, phoneNo string, lang string) (*User, *Error)
	CreateUser(user User, lang string) (interface{}, *Error)
	UpdateUserByID(userID interface{}, columns interface{}, lang string) *Error

	//###########  OTP
	// GetOTP - returns the most current otp
	GetOTP(email string, phoneNo string, otpFor string, lang string) (*OTP, *Error)
	GetOTPs(email string, phoneNo string, otpFor string, offset int64, limit int64, lang string) ([]OTP, *Error)
	// CreateOTP - save otp to db
	CreateOTP(otp OTP, lang string) (interface{}, *Error)
	UpdateOTPByID(otpID interface{}, columns interface{}, lang string) *Error

	//########### Sessions
	CreateSession(session Session, lang string) (interface{}, *Error)
	GetSession(refreshToken string, lang string) (*Session, *Error)

	//########### Push Tokens
	CreateOrUpdatePushToken(pushToken PushToken, lang string) *Error
	GetPushToken(deviceID string, lang string) (*PushToken, *Error)
	GetPushTokensForUserID(userID interface{}, lang string) ([]PushToken, *Error)
	GetPushTokens(userIDs []interface{}, lang string) ([]PushToken, *Error)
	GetAllPushTokens(lang string) ([]PushToken, *Error)
}

Database - Database interface, all db need to implement this

type Error

type Error struct {
	Code    int
	Message string
}

Error - error returned from API

func ChangePassword

func ChangePassword(db Database, lang string, params map[string]interface{}, pwdCheckCallback PwdCheckFunc, pwdHashCallback PwdHashFunc) (map[string]interface{}, *Error)

ChangePassword - changes password of a user

func GenerateAccessToken

func GenerateAccessToken(userID interface{}) (string, *Error)

GenerateAccessToken - generates access token

func GenerateOTP

func GenerateOTP(db Database, lang string, params map[string]interface{}, sendOTPCallback func(email, phoneNo, verifCode string)) (map[string]interface{}, *Error)

GenerateOTP - first step in registration, only email/phone is taken from user and otp code sent

func GenerateRefreshToken

func GenerateRefreshToken(userID interface{}) (string, *Error)

GenerateRefreshToken - generates refresh token

func GenerateToken

func GenerateToken(userID interface{}, expireMins int, params map[string]interface{}) (string, *Error)

GenerateToken - generates signed token

func IsValidPhoneNumber

func IsValidPhoneNumber(phoneNumber string, countryCode string, lang string) (string, *Error)

IsValidPhoneNumber - check whether phone number is valid or not returns the number if valid, else nil

func IsValidToken

func IsValidToken(tokenStr string) (map[string]interface{}, *Error)

IsValidToken - check if jwt token is valid if no error then token is valid return: claims map, error

func Login

func Login(db Database, lang string, params map[string]interface{}, pwdCheckCallback PwdCheckFunc) (map[string]interface{}, *Error)

Login returns access_token if correct username and password are given.

func NewError

func NewError(lang string, errCode int) *Error

NewError - creates an error object for the given error code

func NewErrorWithMessage

func NewErrorWithMessage(errCode int, message string) *Error

NewErrorWithMessage - creates an error object with message

func Register

func Register(db Database, lang string, params map[string]interface{}, pwdHashCallback PwdHashFunc) (map[string]interface{}, *Error)

Register - register user

func ResetPassword

func ResetPassword(db Database, lang string, params map[string]interface{}, pwdHashCallback PwdHashFunc) (map[string]interface{}, *Error)

ResetPassword - reset password of a user

func Token

func Token(db Database, lang string, params map[string]interface{}) (map[string]interface{}, *Error)

Token - refresh access_token using your refresh_token

func UpdatePushToken added in v0.90.2

func UpdatePushToken(db Database, lang string, params map[string]interface{}) (map[string]interface{}, *Error)

UpdatePushToken - update push device token

func VerifyOTP

func VerifyOTP(db Database, lang string, params map[string]interface{}) (map[string]interface{}, *Error)

VerifyOTP - verify otp

type Map

type Map map[string]interface{}

Map is a convenient alias for a map[string]interface{} map, useful for dealing with JSON/BSON in a native way. For instance:

Map{"a": 1, "b": true}

type OTP

type OTP struct {
	ID          interface{} `json:"id" bson:"_id,omitempty"`
	PhoneNumber string      `json:"phone_number"`
	Email       string      `json:"email"`
	Code        string      `json:"-"`

	//otp for REGISTER, RESET, 2FA etc
	OTPFor         string    `json:"otp_for"`
	VerificationID string    `json:"verification_id"`
	VerifiedAt     null.Time `json:"verified_at"`
	ExpiresAt      null.Time `json:"expires_at"`
	CreatedAt      null.Time `json:"created_at"`
}

OTP - one time password

type PushToken added in v0.90.2

type PushToken struct {
	ID        interface{} `json:"id" bson:"_id,omitempty"`
	DeviceID  string      `json:"device_id"`
	DeviceOS  string      `json:"device_os"`
	PushToken string      `json:"push_token"`
	UserID    interface{} `json:"user_id"`
	CreatedAt null.Time   `json:"created_at"`
	UpdatedAt null.Time   `json:"updated_at"`

	IPAddr    string `json:"ip_addr"`
	UserAgent string `json:"user_agent"`
}

PushToken - push notification tokens

type PwdCheckFunc

type PwdCheckFunc = func(hashedPwd string, plainPwd string) bool

PwdCheckFunc - function to check if hashed and plain passwords match

type PwdHashFunc

type PwdHashFunc = func(plainPassword string) string

PwdHashFunc - function to hash a plain password

type SQLRepository

type SQLRepository struct {
	DB *gorm.DB
}

SQLRepository queries the database and returns results to the controller Add your methods here for the handler functions your create in the controller

func (*SQLRepository) Close added in v0.90.6

func (r *SQLRepository) Close() error

Close - closes the db

func (*SQLRepository) CreateOTP

func (r *SQLRepository) CreateOTP(otp OTP, lang string) (interface{}, *Error)

CreateOTP - creates one time password

func (*SQLRepository) CreateOrUpdatePushToken added in v0.90.2

func (r *SQLRepository) CreateOrUpdatePushToken(pushToken PushToken, lang string) *Error

CreateOrUpdatePushToken - creates/updates push token

func (*SQLRepository) CreateRecord

func (r *SQLRepository) CreateRecord(tableName string, record interface{}, lang string) *Error

CreateRecord - create a record record is a reference to struct, eg &user

func (*SQLRepository) CreateSession

func (r *SQLRepository) CreateSession(session Session, lang string) (interface{}, *Error)

CreateSession - creates a session

func (*SQLRepository) CreateUser

func (r *SQLRepository) CreateUser(user User, lang string) (interface{}, *Error)

CreateUser - creates a user

func (*SQLRepository) GetAllPushTokens added in v0.91.4

func (r *SQLRepository) GetAllPushTokens(lang string) ([]PushToken, *Error)

GetAllPushTokens - get all push tokens

func (*SQLRepository) GetOTP

func (r *SQLRepository) GetOTP(email string, phoneNo string, otpFor string, lang string) (*OTP, *Error)

GetOTP - get otp by using email/phoneNo

func (*SQLRepository) GetOTPs added in v0.90.2

func (r *SQLRepository) GetOTPs(email string, phoneNo string, otpFor string, offset int64, limit int64, lang string) ([]OTP, *Error)

GetOTPs - get otps by using email/phoneNo

func (*SQLRepository) GetPushToken added in v0.90.2

func (r *SQLRepository) GetPushToken(deviceID string, lang string) (*PushToken, *Error)

GetPushToken - get push token by deviceID

func (*SQLRepository) GetPushTokens added in v0.90.3

func (r *SQLRepository) GetPushTokens(userIDs []interface{}, lang string) ([]PushToken, *Error)

GetPushTokens - get push tokens for user id list

func (*SQLRepository) GetPushTokensForUserID added in v0.90.3

func (r *SQLRepository) GetPushTokensForUserID(userID interface{}, lang string) ([]PushToken, *Error)

GetPushTokensForUserID - get push tokens for specific user - (multiple login with same account on different devices)

func (*SQLRepository) GetRecord

func (r *SQLRepository) GetRecord(tableName string, tableColumns string, inRecordID interface{}, resultRecord interface{}, lang string) *Error

GetRecord - get single record

func (*SQLRepository) GetSession

func (r *SQLRepository) GetSession(refreshToken string, lang string) (*Session, *Error)

GetSession - get session by refresh token

func (*SQLRepository) GetUserBy

func (r *SQLRepository) GetUserBy(email string, phoneNo string, lang string) (*User, *Error)

GetUserBy - get a user by using email/phonenumber

func (*SQLRepository) Init

func (r *SQLRepository) Init(config *Configuration) error

Init - initialize

func (*SQLRepository) UpdateOTPByID

func (r *SQLRepository) UpdateOTPByID(otpID interface{}, columns interface{}, lang string) *Error

UpdateOTPByID - updates otp by using ID columns map[string]interface{}

func (*SQLRepository) UpdateRecordByID

func (r *SQLRepository) UpdateRecordByID(tableName string, inRecordID interface{}, columns interface{}, lang string) *Error

UpdateRecordByID - update a record by id. the id in the table has to be "id" columns is either map[string]interface{} or a struct

func (*SQLRepository) UpdateUserByID

func (r *SQLRepository) UpdateUserByID(userID interface{}, columns interface{}, lang string) *Error

UpdateUserByID - updates user by using ID columns map[string]interface{}

type Session

type Session struct {
	ID           interface{} `json:"id" bson:"_id,omitempty"`
	UserID       interface{} `json:"user_id"`
	DeviceID     string      `json:"device_id"`
	DeviceName   string      `json:"device_name"`
	RefreshToken string      `json:"refresh_token"`
	CreatedAt    null.Time   `json:"created_at"`

	IPAddr    string `json:"ip_addr"`
	UserAgent string `json:"user_agent"`
}

Session - one time password

type User

type User struct {
	ID          interface{} `json:"id" bson:"_id,omitempty"`
	Name        string      `json:"name"`
	Password    string      `json:"-"`
	Email       string      `json:"email"`
	PhoneNumber string      `json:"phone_number"`
	PhotoURL    string      `json:"photo_url"`
	CreatedAt   null.Time   `json:"created_at"`
}

User holds information about application users

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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