lgn

package
v0.0.0-...-fe173bb Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2024 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package lgn implements an internal login database; users are stored in a JSON file; contains convenience handlers for user retrieval and password change; contains login by hashed URL and login by hash ID; contains profiles - groups of attributes for users. Filename must be given as command line argument or environment variable. Access to the logins data is threadsafe.

Index

Constants

This section is empty.

Variables

View Source
var LgnsPath = path.Join(".", "logins.json")

LgnsPath is obtained by ENV variable or command line flag in main package. Being set from the main package. Holds the relative path and filename to look for; could be ".lgn/logins.json". Relative to the app main dir.

Functions

func AddTestLogin

func AddTestLogin()

AddTestLogin adds a systemtest login. This func is only called by test funcs.

func ChangePassword

func ChangePassword(w http.ResponseWriter, r *http.Request) (string, error)

ChangePassword takes values from request.Form and tries change the user's password. The result is updated in the session "login" type.

func ChangePasswordPrimitiveCoreH

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

ChangePasswordPrimitiveCoreH has *no* outer HTML scaffold - for more, see ChangePasswordPrimitive

func ChangePasswordPrimitiveH

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

ChangePasswordPrimitiveH has outer HTML scaffold - for more, see ChangePasswordPrimitive

func ComputeMD5Password

func ComputeMD5Password(u, p, salt string) string

ComputeMD5Password is deliberately not a method

func CreateAnonymousIDCoreH

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

CreateAnonymousIDCoreH has *no* outer HTML scaffold - for more, see CreateAnonymousID seems unused

func CreateAnonymousIDH

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

CreateAnonymousIDH has outer HTML scaffold - for more, see CreateAnonymousID

func Example

func Example() *loginsT

Example writes a single login to file, to be extended or adapted

func FormToken

func FormToken() string

FormToken returns a form token. User independent. Should we add the user name into the hashed base?

func GenerateHashIDs

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

GenerateHashIDs encodes integer IDs into a kind of base64 encoded string.

func GenerateHashesH

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

GenerateHashesH is a admin UI to create login hashes for specific survey and user profile. See LoginByHash() for the construction of the check string.

func GeneratePassword

func GeneratePassword(length int) string

GeneratePassword creates a password of requested length

func GeneratePasswordH

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

GeneratePasswordH is a convenience func to generate passwords via http request. URL parameter len specifies the password length.

func GeneratePwFromChars

func GeneratePwFromChars(chars []byte, length int) string

GeneratePwFromChars uses chars to create a password of requested length

func Get

func Get() *loginsT

Get provides access to the logins data. It is essential to return a pointer, otherwise the unlocking of the returned struct does not work.

func HashIDDecodeFirst

func HashIDDecodeFirst(encoded string) int

HashIDDecodeFirst turns a string into a slice of integers and returns the first integer

func IsFound

func IsFound(err error) bool

IsFound checks the error argument, if it says user found - but wrong password.

func Load

func Load(r io.Reader)

Load reads from a JSON file. No method to loginsT, no pointer receiver; We could only *copy*: *c = *newCfg

func LoadH

func LoadH(w http.ResponseWriter, req *http.Request)

LoadH is a convenience func to reload logins via http request. It reloads logins from json file and checks for a specific login

func LoginByHash

func LoginByHash(w http.ResponseWriter, r *http.Request) (bool, error)

LoginByHash first checks for direct login; extra short and preconfigured in config.json; last part of the path - moved into h;

LoginByHash then takes request values "u" and hash "h" - and not any password; it checks the hash against the values except "h"; any other request parameters are sorted and included into the hashing check; extended by loginsT.Salt. reduced by those in 'exempted';

request values "h" without an "u" are considered direct login attempts, where the hash actually represents a user ID.

On success, function creates a logged in user out of nothing by the name of u. This user gets assigned the params/values as role-names/values.

On wrong hashes, it returns the difference as error. Be careful not to show the error to the end user.

func LoginPrimitiveCoreH

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

LoginPrimitiveCoreH has *no* outer HTML scaffold - for more, see loginPrimitive

func LoginPrimitiveH

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

LoginPrimitiveH has outer HTML scaffold - for more, see loginPrimitive

func LoginURL

func LoginURL(userName, surveyID, waveID, profile string, optHash ...string) string

LoginURL returns a URL plus a query fragment,

func LoginWithoutID

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

LoginWithoutID creates a hash ID and forwards to direct login /d - LoginByHashID

the user ID is created from unix time; plus some in-memory counter

it's called permalink in subsequent logic

it's related to CreateAnonymousID but the ID comes from an internal timestamp plus atomic counter, it is not created from coarse personal attributes (such as first letter of father's name)

func LogoutH

func LogoutH(w http.ResponseWriter, r *http.Request) error

LogoutH is a convenience handler to logout via http request

func Md5Str

func Md5Str(buf []byte) string

Md5Str computes the MD5 hash of a byte slice; MD5 consists 16 bytes of number. We encode these 16 bytes into a Base64 encoded string suitable for URLs. Such Base64-for-URL encoded MD5 hash consist of 23 characters.

Now we want to reduce that length to get short login URLs. The safe line length for emails is 70 character. stackoverflow.com/questions/11794698 suggests maximum size of 70 or 76 characters

We can simply cut off some of the 23 characters, since MD5 has good avalanching properties.

For questionnaires without large monetary rewards, a hash length of 5 => 64^^5 = 1.073.741.824 combinations is sufficient to discourage brute force attacks.

Our URL now has 64 characters: https://survey2.zew.de/?u=1000&sid=fmt&wid=2019-06&h=57I7U&p=12

func OuterHTMLPost

func OuterHTMLPost(htmlTitle, content string) string

OuterHTMLPost wraps parameter content into a HTML 5 scaffold and a form tag

func Query

func Query(userName, surveyID, waveID, profile string, optHash ...string) string

Query returns a query fragment, using the expected param names u, sid, wid, h See also userAttrs{}

func ReloadH

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

ReloadH removes the existing questioniare from the session, reading it anew from the questionnaire template JSON file, allowing to start anew

func SaveH

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

SaveH is a convenience func to save logins file via http request.

func ShufflesToCSV

func ShufflesToCSV(w http.ResponseWriter, req *http.Request)

ShufflesToCSV computes random but deterministic shufflings for usage outside the app

func ValidateAndLogin

func ValidateAndLogin(w http.ResponseWriter, r *http.Request) error

ValidateAndLogin takes request values "username" and "password". Searches for matching user in the internal JSON database and stores that user into the session under key "login".

func ValidateFormToken

func ValidateFormToken(arg string) error

ValidateFormToken checks tokens against current hour - back to n previous hours. Plus one more for bounding glitches / border crossing when the rounding jumps from 12:59 to 13:00. i.e. FormTimeout := 2 lower bound := -4 => Checking token against current hour, previous hour, second previous hour, third previous hour

Types

type LoginT

type LoginT struct {
	User     string            `json:"user"`
	Email    string            `json:"email"`
	Group    string            `json:"-"`     // Derived from email domain - or LDAP org
	Provider string            `json:"-"`     // twitter, facebook, ... or hash, anonymous/direct, JSON, LDAP
	Roles    map[string]string `json:"roles"` // i.e. admin: true, can only be set via JSON config; therefore safe
	Attrs    map[string]string `json:"attrs"` // i.e. country: Poland, gender: female, height: 188, a few keys can set via URL params, these are unsafe.

	PassInitial    string `json:"pass_initial"`       // For first login - unencrypted - grants restricted access to change password only
	IsInitPassword bool   `json:"is_init_password"`   // Indicates authentication against PassInitial
	PassMd5        string `json:"pass_md5,omitempty"` // Encrypted password, created from login, permanent password, salt
}

LoginT must be exported, *not* because we need to pass a type to sessx.GetObject

loginIntf, ok := sess.EffectiveObj(key)
if !ok {
	// log.Printf("key %v for LoginT{} is not in session", key)
	return &LoginT{}, false, nil
}
l, ok := loginIntf.(LoginT)
if !ok {
	return &LoginT{}, false, fmt.Errorf("key %v for LoginT{} does not point to lgn.LoginT{} - but to %T", key, loginIntf)
}

but because we need to declare variables of this type

type TplDataT struct {
	...
	L      lgn.LoginT
	...
}

func FromSession

func FromSession(w io.Writer, r *http.Request) (*LoginT, bool, error)

FromSession loads a login from session; second return value contains 'is set'.

func LoggedInCheck

func LoggedInCheck(w io.Writer, r *http.Request, roles ...string) (l *LoginT, loggedIn bool, err error)

LoggedInCheck checks, whether as user is logged in, and checks whether he has the required roles; l is always initialized and never nil

func (*LoginT) DeleteFiles

func (l *LoginT) DeleteFiles()

DeleteFiles deletes all JSON files

func (*LoginT) HasRole

func (l *LoginT) HasRole(role string) bool

HasRole checks the login for a particular role, for instance "admin"

func (*LoginT) QuestPath

func (l *LoginT) QuestPath(suffixFN ...string) string

QuestPath returns the path to the JSON *user* questionnaire, Similar to qst.QuestionnaireT.FilePath1() See also userAttrs{}. Param suffix is appended to

func (*LoginT) SetInitPW

func (l *LoginT) SetInitPW(salt string)

SetInitPW sets an init password

Directories

Path Synopsis
Package shuffler creates slices of integers random, but reproducible; based on the ID of the user; classes of users see the same random order each time they visit; each page has a different randomization of appropriate length.
Package shuffler creates slices of integers random, but reproducible; based on the ID of the user; classes of users see the same random order each time they visit; each page has a different randomization of appropriate length.

Jump to

Keyboard shortcuts

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