handlers

package
v0.0.0-...-dfdf941 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2021 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const SigninSessionTokenHeader = "SignInSessionToken"

Variables

View Source
var UserJSONSchema *jsonapi.Schema

Functions

func BeginLogin

func BeginLogin(userService UserService, web *webauthn.WebAuthn) gin.HandlerFunc

func BeginRegistration

func BeginRegistration(userService UserService, web *webauthn.WebAuthn) gin.HandlerFunc

func ConfirmToken

func ConfirmToken(userService UserService) gin.HandlerFunc

swagger:operation POST /totp/confirm confirm

--- summary: Confirm TOTP QR Code description: |

Confirming QR code is part of enabling TOTP process. User will be shown QR code on screen and will be asked to scan the QR
code using his/her authenticator. Entering the TOTP code shown on the authenticator confirms that the device's time
is in sync. Entering also confirms that TOTP calculation algorithm on both authenticator and server work as expected.
Foregoing confirmation means user's TOTP can be rejected during authentication. This also ensures that user does
have access to an working authenticator.

tags:

  • totp

parameters:

  • in: body name: totp description: TOTP code schema: type: object required:
  • totp properties: totp: type: string example: 467292

produces:

  • application/json

responses:

'200':
  description: confirmation successful
  schema:
    type: object
    properties:
      status:
        type: string
        description: confirmation status
        example: totp enabled
'400':
  description: confirmation failed
  schema:
    type: object
    properties:
      status:
        type: string
        description: confirmation status
        example: totp invalid
'401':
  description: problem with retrieving user from authorization header
'500':
  description: internal server error

func DecodeToken

func DecodeToken(tokenString, secret string) (map[string]interface{}, error)

DecodeToken decodes jwt token then returns claims in map

func DeleteUser

func DeleteUser(userService UserService) gin.HandlerFunc

swagger:operation DELETE /users/{id} deleteuser

--- summary: Delete user profile tags:

  • profile

produces:

  • application/json

responses:

'200':
  description: user profile deleted

security:

  • bearer_token: []

func DoesRedirectURIMatch

func DoesRedirectURIMatch(redirectURI string) bool

func EncodeOAuth2Token

func EncodeOAuth2Token(jti, issuer, user, client, scope, secret string, ttl time.Duration) (string, error)

EncodeID signs id

func EncodeToken

func EncodeToken(userID, secret, issuer string, ttl time.Duration) (string, time.Time, error)

EncodeID signs id

func FinishLogin

func FinishLogin(userService UserService, web *webauthn.WebAuthn) gin.HandlerFunc

func FinishRegistration

func FinishRegistration(userService UserService, web *webauthn.WebAuthn) gin.HandlerFunc

func GetClientName

func GetClientName(userService UserService) gin.HandlerFunc

func GetJWTSecretForUser

func GetJWTSecretForUser(payloadRaw string, userService UserService) (string, error)

func GetUser

func GetUser(userService UserService) gin.HandlerFunc

swagger:operation GET /users/{id} getuser

--- summary: "Get user profile" tags:

  • profile

produces:

  • application/json

responses:

'200':
  description: user profile
  schema:
    "$ref": "#/definitions/JSONAPIUserSignupResponse"

security:

  • bearer_token: []
  • oauth2:
  • 'read:profile'

func IsTOTPValid

func IsTOTPValid(user User, token string) bool

func MarshalUser

func MarshalUser(uri string, schema *jsonapi.Schema, user User) (string, error)

func NewTOTPJson

func NewTOTPJson(userService UserService, totpIssuerName string) gin.HandlerFunc

swagger:operation GET /totp/qr-code-json qrcodejson

--- summary: "New TOTP QR code" description: |

New TOTP QR code image is generated in PNG format. The image is then encoded in BASE64 and returned back to the client
in JSON response. The new TOTP QR code won't be associated with the user's account unless `/totp/confirm` endpoint is provided with
the TOTP code from the authenticator device. Refer to <a href="/accounts/redoc.html#operation/confirm">**Confirm TOTP QR Code**</a>
documentation for details.

tags:

  • totp

produces:

  • application/json

responses:

'200':
  description: QR code image PNG encoded in base64
  schema:
    type: object
    properties:
      payload:
        type: string
        description: PNG image encoded in base64
'401':
  description: problem with retrieving user from authorization header
'500':
  description: internal server error

func NewTOTPRaw

func NewTOTPRaw(userService UserService, totpIssuerName string) gin.HandlerFunc

Hiding endpoint to not to confuse developer reading the API

func OAuth2AccessToken

func OAuth2AccessToken(userService UserService) gin.HandlerFunc

swagger:operation POST /oauth2/access_token oauth2accesstoken

--- summary: OAuth2 Access Token description: |

  Exchange code for access token. Access token is in JWT format. The payload looks like the following when it's decoded.
  ```
   {
     "jti":   jti,
     "iss":   issuer,
     "sub":   user,
     "aud":   client,
     "iat":   1596747095,
     "exp":   1596747095,
     "scope": scope
	  }
  ```

consumes:

  • application/x-www-form-urlencoded

tags:

  • oauth2

parameters:

  • in: "body" name: "body" description: HTML form containing the following OAuth2 fields required: true schema: type: object properties: grant_type: type: string require: true example: authorization_code code: type: string example: f7cd9875-8386-4d16-97ef-7ae858ebe4c2 client_id: type: string example: 352b6e64-e498-4307-b64d-ec9e5b9da65c client_secret: type: string example: 1234567 redirect_uri: type: string example: http://www.example.com/oauth2/redirect

produces:

  • application/json

responses:

'200':
  description: OAuth2 access token response
  schema:
    type: object
    "$ref": "#/definitions/AccessTokenResponse"

security: []

func OAuth2Authorize

func OAuth2Authorize(userService UserService) gin.HandlerFunc

swagger:operation POST /oauth2/authorize oauth2authorize

--- summary: "OAuth2 Authorize" description: |

Handles OAuth2 authorization. Only grant type of `code` has been implemented.
Refer to <a href="https://oauth.net/2/">**OAuth2**</a> documentation for details. The OAuth2 `client` signup is
missing from UI as well as the User API endpoints. The OAuth2 `client` signup will be added in the future.
User is expected to be logged in when this call is made.

tags:

  • oauth2

parameters:

  • in: "body" name: "body" description: "Authorization Request" required: true schema: "$ref": "#/definitions/AuthorizationRequest"

produces:

  • application/json

responses:

'200':
  description: authorization code response
  schema:
    type: object
    "$ref": "#/definitions/AuthorizationResponse"

func OAuth2Scope

func OAuth2Scope(userService UserService) gin.HandlerFunc

func ParseAuthTokenFromAuthorizationHeader

func ParseAuthTokenFromAuthorizationHeader(req *http.Request) (string, error)

func PreflightOptions

func PreflightOptions() gin.HandlerFunc

PreflightOptionsHandler handles preflight OPTIONS

func QR

func QR(url string) ([]byte, error)

func Signin

func Signin(userService UserService, ttl time.Duration, issuer string) gin.HandlerFunc

swagger:operation POST /signin signin

--- summary: Signin description: |

Here is the list of authentication types

|      1st Factor             |          2nd Factor       |     Security                      |
|-----------------------------|---------------------------|-----------------------------------|
|      Password               |             None          | Weak - password can be guessed    |
|      Password               |             TOTP          | Medium - prone to phishing attack |
|      Password               |             WebAuthn      | Strong                            |

**Password Only**

Successful password authentication call to this endpoint sends back http status code `200` with JWT auth token.

**Password + TOTP**

This is two factor authentication. User's security settings must have TOTP enabled in order for this second
factor authentication to be presented to the user after a successful password authentication.
Successful password auth call to this endpoint results in the server sending back http status code `422` with
`signin_session_token` which represents successful password authentication. The client at that point is
expected to send TOTP with received `signin_session_token`. This endpoint will validate both data. Once valid the
endpoint will send back http status code `200` with JWT auth token.

<img src="/accounts/assets/totp_flow.png" alt="TOTP Flow">

**Password + WebAuthn**

This is two factor authentication. User's security settings must have WebAuthn enabled in order for this second
factor authentication to be presented to the user after a successful password authentication. Calling WebAuthn
endpoint requires working with browser's <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API">**WebAuthn API**</a>
That brings a bit of challenge to automated testing. Testing tool can not simply pass in some value to this restful
service endpoint. The tool needs to call browser's WebAuthn API to have the browser initiate a communication
with the user's physical authenticator device. Although it is theoretically possible to emulate the physical authenticator
using <a href="https://github.com/github/SoftU2F/">**software**</a>, there isn't a software authenticator that is suitable
for fully automated testing. Therefore, testing of WebAuthn flow will remain as manual.

<img src="/accounts/assets/webauthn_flow.png" alt="WebAuthn Flow">

tags:

  • account

parameters:

  • in: "body" name: "body" description: "User Credentials" required: true schema: "$ref": "#/definitions/CredentialsBase"

produces:

  • application/json

responses:

'200':
  description: access granted
  schema:
    type: object
    "$ref": "#/definitions/JWTToken"
'401':
  description: access denied
  schema:
    type: object
    properties:
      code:
        type: integer
        description: error code
        example: 4300
      message:
        type: string
        description: error message
        example: Check login name or password
'422':
  description: missing data
  schema:
    type: object
    properties:
      code:
        type: integer
        description: error code
        example: 4800
      message:
        type: string
        description: error message
        example: TOTP required
      signin_session_token:
        type: string
        description: signin session token
        example: MzM4OGNkMWEtNmQyNC00MDQ1LWJmYzctMWJlMzM3ZTk1NDQ5

security: [] x-codeSamples:

  • lang: curl-password source: | curl -X POST \ https://accounts.7onetella.net/signin \ -H 'Content-Type: application/json' \ -d '{ "username": "john.smith@example.com", "password": "password1234" }'
  • lang: curl-totp source: | curl -X POST \ https://accounts.7onetella.net/signin \ -H 'Content-Type: application/json' \ -d '{ "signin_session_token": "YjcxYmE0MjQtMGY1MS00ZDI0LTk4NDAtYjhiM2IwNzY5ZDNk", "totp": "592918" }'

func Signup

func Signup(userService UserService) gin.HandlerFunc

swagger:operation POST /users signup

--- summary: Signup description: |

User signup using JSON:API document format as input

tags:

  • account

parameters:

  • in: "body" name: "body" description: "User JSON:API Document" required: true schema: "$ref": "#/definitions/JSONAPIUserSignup"

produces:

  • application/json

responses:

'200':
  description: user created
  schema:
    type: object
    "$ref": "#/definitions/JSONAPIUserSignupResponse"
'500':
  description: internal server issue

security: []

func UnmarshalUser

func UnmarshalUser(payload []byte, schema *jsonapi.Schema) (User, error)

func UpdateUser

func UpdateUser(userService UserService) gin.HandlerFunc

swagger:operation PATCH /users/{id} updateuser

--- summary: Updates user profile tags:

  • profile

parameters:

  • in: "body" name: "body" description: "User JSON:API Document" required: true schema: "$ref": "#/definitions/JSONAPIUserSignup"

produces:

  • application/json

responses:

'204':
  description: user profile updated

security:

  • bearer_token: []
  • oauth2:
  • 'write:profile'

Types

type Credentials

type Credentials struct {
	// this field
	Type string `json:"type"`

	Username string `json:"username"`

	Password string `json:"password"`

	SigninSessionToken string `json:"signin_session_token"`

	TOTP string `json:"totp"`

	WebAuthnSessionToken string `json:"webauthn_session_token"`
}

This struct combines all the attributes from PasswordCredentials, TOTPCredentials and WebauthnCredentials. These three are used for generating swagger documentation. This struct is the real struct used internally during authentication.

func (Credentials) IsSigninSessionTokenPresent

func (c Credentials) IsSigninSessionTokenPresent() bool

func (Credentials) IsTOTPCodePresent

func (c Credentials) IsTOTPCodePresent() bool

func (Credentials) IsUsernamePresent

func (c Credentials) IsUsernamePresent() bool

func (Credentials) IsWebauthnTokenPresent

func (c Credentials) IsWebauthnTokenPresent() bool

type CredentialsBase

type CredentialsBase struct {
	//
	// discriminator: true
	Type string `json:"type"`
}

CredentialsBase represents user credentials type

swagger:model

type CustomClaims

type CustomClaims struct {
	jwt.StandardClaims
	Scope string `json:"scope"`
}

func DecodeTokenAsCustomClaims

func DecodeTokenAsCustomClaims(tokenString, secret string) (CustomClaims, error)

DecodeToken decodes jwt token then returns claims in map

func ExtractClaimsFromPayload

func ExtractClaimsFromPayload(s string) (*CustomClaims, error)

func (CustomClaims) Valid

func (cc CustomClaims) Valid() error

type JWTAuth

type JWTAuth struct {
	ClaimKey string
	TTL      time.Duration
}

func (JWTAuth) RefreshToken

func (a JWTAuth) RefreshToken(userService UserService, issuer string) gin.HandlerFunc

SigninHandlerFunc signs in user

func (JWTAuth) TokenValidator

func (a JWTAuth) TokenValidator(userService UserService) gin.HandlerFunc

type JWTToken

type JWTToken struct {
	// jwt token
	// required: true
	// example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiI3b25ldGVsbGEiLCJleHAiOjE2MDQ1NTYyMjcsImlhdCI6MTYwNDU1MjYyNywiaXNzIjoiN29uZXRlbGxhIiwic3ViIjoiMDA1ZDBiYzMtN2NmYi00NzkxLTg0ZDktZjFkN2IzMmJiM2YxIn0.kY5BpagojMbkn0T2vnEXYeQ_bRMriDmW6iEG3D7GQQI
	Token string `json:"token"`
	// token expiration date
	// required: true
	// example: 1604556227
	Expiration int64 `json:"exp"`
}

This is JWT Auth Token

swagger:model JWTToken

type PasswordCredentials

type PasswordCredentials struct {
	// swagger:allOf com.7onetella.PasswordCredentials
	CredentialsBase
	// username
	//
	// required: true
	// example: john.smith@example.com
	Username string `json:"username"`
	// password
	//
	// required: true
	// example: password1234
	Password string `json:"password"`
}

password_credentials represents user password credentials

swagger:model password_credentials

type TOTPCredentials

type TOTPCredentials struct {
	// swagger:allOf com.7onetella.TOTPCredentials
	CredentialsBase
	// token received after successful password authentication
	//
	// required: true
	// example: MzM4OGNkMWEtNmQyNC00MDQ1LWJmYzctMWJlMzM3ZTk1NDQ5
	SigninSessionToken string `json:"signin_session_token"`
	// totp code from authenticator device
	//
	// required: true
	// example: 327621
	TOTP string `json:"totp"`
}

totp_credentials represents user totp credentials

swagger:model totp_credentials

type WebauthnCredentials

type WebauthnCredentials struct {
	// swagger:allOf com.7onetella.WebauthnCredentials
	CredentialsBase
	// token received after successful password authentication
	//
	// required: true
	// example: MzM4OGNkMWEtNmQyNC00MDQ1LWJmYzctMWJlMzM3ZTk1NDQ5
	SigninSessionToken string `json:"signin_session_token"`
	// token received after successful webauthn authentication
	//
	// required: true
	// example: ZDkyZjJkNWMtNGU2Ny00ZGRmLWI2ZGQtOTExNTcyYzIwNWFk
	WebauthnSessionToken string `json:"webauthn_session_token"`
}

webauthn_credentials represents user webauthn credentials

swagger:model webauthn_credentials

Jump to

Keyboard shortcuts

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