utils

package
v0.0.0-...-c9f6891 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2024 License: Apache-2.0 Imports: 52 Imported by: 4

Documentation

Overview

Copyright 2020 Pantacor Ltd.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Package utils is licensed as follows:

Copyright 2018 Pantacor Ltd.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Package utils package to manage extensions of the oauth protocol

Index

Constants

View Source
const (
	// EnvPantahubProductName Pantahub Product Name (branding)
	EnvPantahubProductName = "PANTAHUB_PRODUCTNAME"

	// EnvPantahubJWTAuthSecret Pantahub JWT Secret. THIS MUST BE SET TO SOMETHING SECRET!!
	// default: "THIS MUST BE CHANGED"
	EnvPantahubJWTAuthSecret = "PANTAHUB_JWT_SECRET"

	// EnvPantahubScryptSecret scrypt secret
	EnvPantahubScryptSecret = "PANTAHUB_SCRYPT_SECRET"

	// EnvPantahubJWTAuthPub Pantahub JWT Public Key. Public RSA key in base64 encoded PEM format
	EnvPantahubJWTAuthPub = "PANTAHUB_JWT_PUB"

	// EnvPantahubJWESecret Pantahub JWE Secret. THIS MUST BE SET TO SOMETHING SECRET!!
	EnvPantahubJWESecret = "PANTAHUB_JWE_SECRET"

	// EnvPantahubJWEPub Pantahub JWE Public Key. Public RSA key in base64 encoded PEM format
	EnvPantahubJWEPub = "PANTAHUB_JWE_PUB"

	// EnvGoogleCaptchaSecret Google Captcha service secret key
	// default: "This must be changed"
	EnvGoogleCaptchaSecret = "GOOGLE_CAPTCHA_SECRET"

	// EnvPantahubUseCaptcha Pantahub Use Captcha. Set if captcha will be used by the API.
	EnvPantahubUseCaptcha = "PANTAHUB_USE_CAPTCHA"

	// EnvPantahubJWTObjectSecret Pantahub JWT Secret. THIS MUST BE SET TO SOMETHING SECRET!!
	// default: "THIS MUST BE CHANGED"
	EnvPantahubJWTObjectSecret = "PANTAHUB_JWT_OBJECT_SECRET"

	// EnvPantahubJWTTimeoutMinutes Pantahub JWT Token Timeout in Minutes
	// default: 60
	EnvPantahubJWTTimeoutMinutes = "PANTAHUB_JWT_TIMEOUT_MINUTES"

	// EnvPantahubRecoverJWTTimeoutMinutes Pantahub JWT Token for password recovery Timeout in Minutes
	// default: 60
	EnvPantahubRecoverJWTTimeoutMinutes = "PANTAHUB_RECOVER_JWT_TIMEOUT_MINUTES"

	// EnvPantahubJWTMaxRefreshMinutes Pantahub JWT Max Refresh timeout in Minutes
	// default: 24 * 60
	EnvPantahubJWTMaxRefreshMinutes = "PANTAHUB_JWT_MAX_REFRESH_MINUTES"

	// EnvPantahubCaCert ca certificate
	EnvPantahubCaCert = "PANTAHUB_CA_CERT"

	// EnvProxyTLSUnlockAuthToken tls authentication secret token
	EnvProxyTLSUnlockAuthToken = "PANTAHUB_PROXY_TLS_AUTH_TOKEN"

	// EnvPantahubCaHost Ca host URL
	EnvPantahubCaHost = "PANTAHUB_CA_HOST"

	// EnvPantahubCaRaUser Ca RA user
	EnvPantahubCaRaUser = "PANTAHUB_CA_RA_USER"

	// EnvPantahubCaRaPass CA RA password
	EnvPantahubCaRaPass = "PANTAHUB_CA_RA_PASS"

	// EnvPantahubCaP12Cert P12 certificate
	EnvPantahubCaP12Cert = "PANTAHUB_CA_P12_CERT"

	// EnvPantahubCaP12Key P12 key
	EnvPantahubCaP12Key = "PANTAHUB_CA_P12_KEY"

	// EnvPantahubCaServiceURL  Ca service URL
	EnvPantahubCaServiceURL = "PANTAHUB_CA_SERVICE_URL"

	// EnvPantahubHost Host you want clients to reach this server under
	// default: localhost
	EnvPantahubHost = "PANTAHUB_HOST"

	// EnvPantahubWWWHost Host you want clients to reach the web-interface
	// default: localhost
	EnvPantahubWWWHost = "PANTAHUB_HOST_WWW"

	// EnvPantahubPort Port you want to make this server available under
	// default: 12365 for http and 12366 for https
	EnvPantahubPort = "PANTAHUB_PORT"

	// EnvPantahubScheme Default scheme to use for urls pointing at this server when we encode
	// them in json or redirect (e.g. for auth)
	// default: http
	EnvPantahubScheme = "PANTAHUB_SCHEME"

	// EnvPantahubAPIVersion not used
	EnvPantahubAPIVersion = "PANTAHUB_APIVERSION"

	// EnvElasticURL Set elasticsearch base URL
	// default: https://es5.pantahub.com
	EnvElasticURL = "ELASTIC_URL"

	// EnvElasticUsername Set elasticsearch basic auth username; if set
	// a Basic auth token will be generated for you from
	// ELASTIC_USERNAME & ELASTIC_PASSWORD
	// default: ""
	EnvElasticUsername = "ELASTIC_USERNAME"

	// EnvElasticPassword Set elasticsearch basic auth password
	// default: ""
	EnvElasticPassword = "ELASTIC_PASSWORD"

	// EnvElasticBearer Set elasticsearch bearer auth token
	// default: ""
	EnvElasticBearer = "ELASTIC_BEARER"

	// EnvFluentPort Set Fluent port to send logs to
	// default: "24224"
	EnvFluentPort = "FLUENT_PORT"

	// EnvFluentHost Set Fluent host to send logs to
	// default: "127.0.0.1"
	EnvFluentHost = "FLUENT_HOST"

	// EnvK8SNamespace Set K8S NAMESPACE info
	// default: "NA"
	EnvK8SNamespace = "K8S_NAMESPACE"

	// EnvK8sNodeName k8s node name
	EnvK8sNodeName = "K8S_NODE_NAME"

	// EnvK8sApiUrl k8s api url to get node information
	EnvK8sApiUrl = "K8S_API_URL"

	// EnvHostName Set HOSTNAME info
	// default: "localhost"
	EnvHostName = "HOSTNAME"

	// EnvPantahubAuth Authentication endpoint to point clients to that need access tokens
	// or need more privileged access tokens.
	// default: $PANTAHUB_SCHEME://$PANTAHUB_HOST:$PANTAHUB_PORT/auth
	EnvPantahubAuth = "PH_AUTH"

	// EnvPantahubSignupPath pantahub signup path
	EnvPantahubSignupPath = "PANTAHUB_SIGNUP_PATH"

	// EnvPantahubPortInt port to listen to on for http on internal interfaces
	// default: 12365
	EnvPantahubPortInt = "PANTAHUB_PORT_INT"

	// EnvPantahubPortIntTLS port to listen to on for https on internal interfaces
	// default: 12366
	EnvPantahubPortIntTLS = "PANTAHUB_PORT_INT_TLS"

	// EnvMailgunDomain domain
	// default: <empty>
	EnvMailgunDomain = "MAILGUN_DOMAIN"

	// EnvMailgunAPIKey api key
	// default: <empty>
	EnvMailgunAPIKey = "MAILGUN_APIKEY"

	// EnvMailgunApiURL mailgun api url
	// default: <empty>
	EnvMailgunApiURL = "MG_URL"

	// EnvMailgunPubAPIKey mailgone pub api key
	// default: <empty>
	EnvMailgunPubAPIKey = "MAILGUN_PUBAPIKEY"

	// EnvMongoHost Hostname for mongodb connection
	// default: localhost
	EnvMongoHost = "MONGO_HOST"

	// EnvMongoPort Port for mongodb connection
	// default: 27017
	EnvMongoPort = "MONGO_PORT"

	// EnvMongoDb Database name for mongodb connection
	// default: pantabase-serv
	EnvMongoDb = "MONGO_DB"

	// EnvMongoUser Database user for mongodb connection
	// default: <none>
	EnvMongoUser = "MONGO_USER"

	// EnvMongoPassword Database password for mongodb connection
	// default: <none>
	EnvMongoPassword = "MONGO_PASS"

	// EnvMongoRs Database password for mongodb connection
	// default: <none>
	EnvMongoRs = "MONGO_RS"

	// EnvMongoSsl connect using ssl to the database
	EnvMongoSsl = "MONGO_SSL"

	// EnvPantahubSaAdminSecret Service Account Admin Secret to use
	// default: <none> (Required!)
	EnvPantahubSaAdminSecret = "PANTAHUB_SA_ADMIN_SECRET"

	// EnvPantahubAdminSecret Comma Separated List of PRNs of users that have pantahub admin role
	// default: <none> (Required for Production!)
	EnvPantahubAdminSecret = "PANTAHUB_ADMIN_SECRET"

	// EnvPantahubAdmins Comma Separated List of PRNs of users that have pantahub admin role
	// default: <none>
	EnvPantahubAdmins = "PANTAHUB_ADMINS"

	// EnvPantahubSubscriptionAdmins Comma Separated List of PRNs of users that have pantahub subscription admin
	// role
	// default: <none>
	EnvPantahubSubscriptionAdmins = "PANTAHUB_SUBSCRIPTION_ADMINS"

	// EnvSMTPHost SMTP host to use for sending mails
	// default: <none>
	EnvSMTPHost = "SMTP_HOST"

	// EnvSMTPPort SMTP port to use for sending mails
	// default: <none>
	EnvSMTPPort = "SMTP_PORT"

	// EnvSMTPUser SMTP user to use for sending mails
	// default: <none>
	EnvSMTPUser = "SMTP_USER"

	// EnvSMTPPass SMTP pass to use for sending mails
	// default: <none>
	EnvSMTPPass = "SMTP_PASS"

	// EnvRegEmail SMTP pass to use for sending mails
	// default: <none>
	EnvRegEmail = "REG_EMAIL"

	// EnvPantahubStorageDriver used to store objects
	EnvPantahubStorageDriver = "PANTAHUB_STORAGE_DRIVER"

	// EnvPantahubS3AccessKeyID access key of s3 storage credentials
	EnvPantahubS3AccessKeyID = "PANTAHUB_S3_ACCESS_KEY_ID"

	// EnvPantahubS3SecretAccessKeyID secret access key of s3 storage credentials
	EnvPantahubS3SecretAccessKeyID = "PANTAHUB_S3_SECRET_ACCESS_KEY"

	// EnvPantahubS3SAnonymousCredentials use anonymous credentials
	EnvPantahubS3SAnonymousCredentials = "PANTAHUB_S3_USE_ANONYMOUS_CREDENTIALS"

	// EnvPantahubS3Region region where to store objects
	EnvPantahubS3Region = "PANTAHUB_S3_REGION"

	// EnvPantahubS3RegionSelection way to select the region
	EnvPantahubS3RegionSelection = "PANTAHUB_S3_REGION_SELECTION"

	// EnvPantahubS3Bucket bucket where to store objects
	EnvPantahubS3Bucket = "PANTAHUB_S3_BUCKET"

	// EnvPantahubS3Endpoint enpoint of s3 server
	EnvPantahubS3Endpoint = "PANTAHUB_S3_ENDPOINT"

	// EnvPantahubS3RegionalConfigMap s3 automatic selection variables
	EnvPantahubS3RegionalConfigMap = "PANTAHUB_S3_CONFIG_MAP"

	// EnvPantahubStoragePath for backing storage
	// default: ../local-s3/
	EnvPantahubStoragePath = "PANTAHUB_STORAGE_PATH"

	// EnvPantahubS3Path deprecated, please use EnvPantahubStoragePath instead
	EnvPantahubS3Path = "PANTAHUB_S3PATH"

	// EnvRestyDebug enable resty client debugging if env is set
	// default: ""
	EnvRestyDebug = "RESTY_DEBUG"

	// EnvPantahubGCAPI Pantahub GC API end point
	EnvPantahubGCAPI = "PANTAHUB_GC_API"

	// EnvPantahubGCRemoveGarbage Pantahub GC garbage removal flag
	EnvPantahubGCRemoveGarbage = "PANTAHUB_GC_REMOVE_GARBAGE"

	// EnvPantahubGCUnclaimedExpiry Pantahub GC UnClaimed expiry for device to mark it as garbage
	EnvPantahubGCUnclaimedExpiry = "PANTAHUB_GC_UNCLAIMED_EXPIRY"

	// EnvPantahubGCGarbageExpiry Pantahub GC garbage expiry time to remove it
	EnvPantahubGCGarbageExpiry = "PANTAHUB_GC_GARBAGE_EXPIRY"

	// EnvPantahubDemoAccountsPasswordService1 Pantahub Demo Account:service1 password
	EnvPantahubDemoAccountsPasswordService1 = "PANTAHUB_DEMOACCOUNTS_PASSWORD_service1"

	// EnvPantahubLogBody enable log requests,responses parameters and bodies
	EnvPantahubLogBody = "PANTAHUB_LOG_BODY"

	// EnvCronJobTimeout is to set the cron job timeout(secs)
	EnvCronJobTimeout = "CRON_JOB_TIMEOUT"

	// EnvGoogleOAuthClientID GOOGLE_OAUTH_CLIENT_ID
	EnvGoogleOAuthClientID = "GOOGLE_OAUTH_CLIENT_ID"

	// EnvGoogleOAuthClientSecret GOOGLE_OAUTH_CLIENT_SECRET
	EnvGoogleOAuthClientSecret = "GOOGLE_OAUTH_CLIENT_SECRET"

	// EnvGithubOAuthClientID GITHUB_OAUTH_CLIENT_ID
	EnvGithubOAuthClientID = "GITHUB_OAUTH_CLIENT_ID"

	// EnvGithubOAuthClientSecret GITHUB_OAUTH_CLIENT_SECRET
	EnvGithubOAuthClientSecret = "GITHUB_OAUTH_CLIENT_SECRET"

	// EnvGitlabOAuthClientID GITLAB_OAUTH_CLIENT_ID
	EnvGitlabOAuthClientID = "GITLAB_OAUTH_CLIENT_ID"

	// EnvGitlabOAuthClientSecret GITLAB_OAUTH_CLIENT_SECRET
	EnvGitlabOAuthClientSecret = "GITLAB_OAUTH_CLIENT_SECRET"

	// EnvPantahubElasticShards PANTAHUB_ELASTIC_SHARDS
	EnvPantahubElasticShards = "PANTAHUB_ELASTIC_SHARDS"

	// EnvPantahubElasticReplicas PANTAHUB_ELASTIC_REPLICAS
	EnvPantahubElasticReplicas = "PANTAHUB_ELASTIC_REPLICAS"

	// EnvPantahub3rdAppLogoMaxSizeKb max size for 3rd party apps logo
	EnvPantahub3rdAppLogoMaxSizeKb = "PANTAHUB_3RD_APP_LOGO_MAX_SIZE_KB"

	// EnvAnonJWTTimeoutMinutes anonimous token timeout
	EnvAnonJWTTimeoutMinutes = "PANTAHUB_ANON_JWT_TIMEOUT"
)
View Source
const (
	// ImageLinkedin linkedin logo image
	ImageLinkedin = "" /* 900-byte string literal not displayed */

	// ImageRd rd logo image
	ImageRd = "" /* 380-byte string literal not displayed */

	// ImageRu ru logo image
	ImageRu = "" /* 416-byte string literal not displayed */

	// ImageTwitter twitter logo image
	ImageTwitter = "" /* 1136-byte string literal not displayed */

	// ImageReddit image of reddit
	ImageReddit = "" /* 11112-byte string literal not displayed */

	ImageLogo = "" /* 8916-byte string literal not displayed */
)
View Source
const (
	// BaseServiceID all services id base string
	BaseServiceID string = "prn:pantahub.com:apis:/"

	// PantahubServiceID Pantahub service ID
	PantahubServiceID string = "prn:pantahub.com:apis:/base"
)

Variables

View Source
var (
	CryptoMethods = &crytoMethods{
		BCrypt: BCryptMethod,
		SCrypt: SCryptMethod,
	}
)

CryptoMethods kind a enum for cryptography methods supported

View Source
var MongoDb string

MongoDb : Holds Mongo Db Name

View Source
var PhScopeArray []Scope = []Scope{}

PhScopeArray List of pantahub base scope names

View Source
var PhScopeNames []string = []string{}

PhScopeNames List of pantahub base scope names

View Source
var PhScopesMap map[string]Scope = map[string]Scope{}

PhScopesMap Map of all scope by type

View Source
var Scopes = &IScopes{
	API: Scope{
		ID:          "all",
		Service:     PantahubServiceID,
		Description: "Complete Access",
	},
	Profile: Scope{
		ID:          "profile",
		Service:     PantahubServiceID,
		Description: "Read/Write Profile",
	},
	ReadProfile: Scope{
		ID:          "profile.readonly",
		Service:     PantahubServiceID,
		Description: "Read only Profile",
	},
	Devices: Scope{
		ID:          "devices",
		Service:     PantahubServiceID,
		Description: "Read/Write devices",
	},
	ReadDevices: Scope{
		ID:          "devices.readonly",
		Service:     PantahubServiceID,
		Description: "Read only devices",
	},
	WriteDevices: Scope{
		ID:          "devices.write",
		Service:     PantahubServiceID,
		Description: "Write only devices",
	},
	UpdateDevices: Scope{
		ID:          "devices.change",
		Service:     PantahubServiceID,
		Description: "Update devices",
	},
	ReadUser: Scope{
		ID:          "user.readonly",
		Service:     PantahubServiceID,
		Description: "Read only user",
	},
	WriteUser: Scope{
		ID:          "user.write",
		Service:     PantahubServiceID,
		Description: "Write only user",
	},
	Trails: Scope{
		ID:          "trails",
		Service:     PantahubServiceID,
		Description: "Read/Write only trails",
	},
	ReadTrails: Scope{
		ID:          "trails.readonly",
		Service:     PantahubServiceID,
		Description: "Read only trails",
	},
	WriteTrails: Scope{
		ID:          "trails.write",
		Service:     PantahubServiceID,
		Description: "Write only trails",
	},
	UpdateTrails: Scope{
		ID:          "trails.change",
		Service:     PantahubServiceID,
		Description: "Update trails",
	},
	Objects: Scope{
		ID:          "objects",
		Service:     PantahubServiceID,
		Description: "Read/Write only objects",
	},
	ReadObjects: Scope{
		ID:          "objects.readonly",
		Service:     PantahubServiceID,
		Description: "Read only objects",
	},
	WriteObjects: Scope{
		ID:          "objects.write",
		Service:     PantahubServiceID,
		Description: "Write only objects",
	},
	UpdateObjects: Scope{
		ID:          "objects.change",
		Service:     PantahubServiceID,
		Description: "Update objects",
	},
	Metrics: Scope{
		ID:          "metrics",
		Service:     PantahubServiceID,
		Description: "Read/Write only metrics",
	},
	ReadMetrics: Scope{
		ID:          "metrics.readonly",
		Service:     PantahubServiceID,
		Description: "Read only metrics",
	},
	WriteMetrics: Scope{
		ID:          "metrics.write",
		Service:     PantahubServiceID,
		Description: "Write only metrics",
	},
	UpdateMetrics: Scope{
		ID:          "metrics.change",
		Service:     PantahubServiceID,
		Description: "Update metrics",
	},
}

Scopes variable with all the posible scopes

Functions

func BsonQuoteMap

func BsonQuoteMap(m *map[string]interface{}) map[string]interface{}

BsonQuoteMap create a new map of quotes with escaped indexes

func BsonUnquoteMap

func BsonUnquoteMap(m *map[string]interface{}) map[string]interface{}

BsonUnquoteMap create a new map of quotes with unescaped indexes

func BuildScopePrn

func BuildScopePrn(serviceID string) string

BuildScopePrn build a scope PRN from a service ID

func CalcBinarySize

func CalcBinarySize(data string) int

CalcBinarySize calculate binary size from a string

func CheckPasswordHash

func CheckPasswordHash(password, hash string, method Method) bool

CheckPasswordHash validate password agains a given hash

func CreateJWE

func CreateJWE(claims interface{}) (string, error)

CreateJWE encrypt a JWT token

func CreateTmpFile

func CreateTmpFile(content []byte, name string, dir string) (string, error)

CreateTmpFile create a temporal file with a content, return and string with the path

func DecodeSha256HexString

func DecodeSha256HexString(shaString string) (sha []byte, err error)

DecodeSha256HexString decode sha string

func GenerateChallenge

func GenerateChallenge() string

GenerateChallenge create challenge string

func GenerateSecret

func GenerateSecret(length int) (string, error)

GenerateSecret generate secret

func GetAPIEndpoint

func GetAPIEndpoint(localEndpoint string) string

GetAPIEndpoint get pantahub api URL endpoint

func GetEnv

func GetEnv(key string) string

GetEnv get environment variable using variable key

func GetMongoClient

func GetMongoClient() (*mongo.Client, error)

GetMongoClient : To Get Mongo Client Object

func GetMongoClientTest

func GetMongoClientTest() (*mongo.Client, error)

GetMongoClientTest : To Get Mongo Client Object

func GetMongoSession

func GetMongoSession() (*mgo.Session, error)

GetMongoSession is the legacy util to access database through old mgo driver

func GetMongoSessionTest

func GetMongoSessionTest() (*mgo.Session, error)

GetMongoSessionTest get a test session of mongo

func HashPassword

func HashPassword(password string, method Method) (string, error)

HashPassword create a hashed version of a string

func IDGetPrn

func IDGetPrn(id primitive.ObjectID, serviceName string) string

IDGetPrn get prn ID

func IDGetPrnLegacy

func IDGetPrnLegacy(id bson.ObjectId, serviceName string) string

IDGetPrnLegacy get prn legaccy information

func InitScopes

func InitScopes()

InitScopes get all scopes names

func IsEmail

func IsEmail(email string) bool

IsEmail check if a string is an email

func IsNick

func IsNick(nick string) bool

IsNick check if a string is a nick

func IsSha256HexString

func IsSha256HexString(shaString string) bool

func IsUserError

func IsUserError(err error) bool

IsUserError check if an error is the type UserError

func MakeLocalS3PathForName

func MakeLocalS3PathForName(name string) (string, error)

MakeLocalS3PathForName create a local S3 path for name

func MatchAllScope

func MatchAllScope(filterScopes []string, requestScopes []string) bool

MatchAllScope serch one scope in all the available scopes

func MatchScope

func MatchScope(filterScopes []string, requestScopes []string) bool

MatchScope serch one scope in all the available scopes

func MergeDefaultProjection

func MergeDefaultProjection(p map[string]interface{}) map[string]interface{}

MergeDefaultProjection merge projection with required values

func MergeMaps

func MergeMaps(base map[string]interface{}, overwrite map[string]interface{}) map[string]interface{}

MergeMaps merge two maps overiding what is in the first map with the second one

func PantahubS3Path

func PantahubS3Path() string

PantahubS3Path get S3 pantahub path from environment

func ParseBase64PemCert

func ParseBase64PemCert(certPemBase64 string) (*x509.Certificate, error)

ParseBase64PemCert parse der certificate to x590 certificate

func ParseJWE

func ParseJWE(raw string, out interface{}) error

ParseJWE decrypt a JWT token

func ParsePEMCertString

func ParsePEMCertString(pemCert []byte) (*x509.Certificate, error)

ParsePEMCertString parse a pem certificate

func ParseScopes

func ParseScopes(scopes []Scope) []string

ParseScopes covert array of scopes on array of string scopes

func PrnGetID

func PrnGetID(prn string) string

PrnGetID make this a nice prn helper tool

func R

func R() *resty.Request

R create a *resty.Request honouring global client settings configurable through environments.

func RT

func RT(timeout int) *resty.Request

func RandString

func RandString(n int) string

func RandStringLower

func RandStringLower(n int) string

func RandStringUpper

func RandStringUpper(n int) string

func RestError

func RestError(w rest.ResponseWriter, err error, message string, statusCode int)

RestError Create a rest error with id and log

func RestErrorUser

func RestErrorUser(w rest.ResponseWriter, err error, message string, statusCode int)

RestErrorUser Create a rest error with id and log

func RestErrorWrapper

func RestErrorWrapper(w rest.ResponseWriter, errorStr string, code int)

RestErrorWrapper wrap the normal rest error in an struct

func RestErrorWrapperUser

func RestErrorWrapperUser(w rest.ResponseWriter, errorStr, userMessage string, code int)

RestErrorWrapperUser wrap the normal rest error in an struct

func RestErrorWrite

func RestErrorWrite(w rest.ResponseWriter, err *RError)

RestErrorWrite write error

func ScopeFilter

func ScopeFilter(filterScopes []Scope, handler rest.HandlerFunc) rest.HandlerFunc

ScopeFilter : Scope Filter for end points

func ScopeStringFilterBy

func ScopeStringFilterBy(s []string, filter, prefix string) []string

func SendResetPasswordEmail

func SendResetPasswordEmail(email, nick, token string) error

SendResetPasswordEmail send reset password to account

func SendVerification

func SendVerification(email, nick, id, u string, urlPrefix string) bool

SendVerification send a verification email

func SendWelcome

func SendWelcome(email, nick, urlPrefix string) error

SendWelcome send a verification email

func StateSha

func StateSha(obj interface{}) (string, error)

StateSha get sha state from a obj

func UserTypeFilter

func UserTypeFilter(filterTypes []accounts.AccountType, handler rest.HandlerFunc) rest.HandlerFunc

UserTypeFilter filter request by user type

func ValidateCaSigned

func ValidateCaSigned(cert *x509.Certificate) error

ValidateCaSigned validate a certificate that has been signed by pantahub CA

func ValidateOwnerSig

func ValidateOwnerSig(pctx context.Context, sig, tokenID, owner, name string, col *mongo.Collection) error

ValidateOwnerSig valdiate a owner signature

func ValidateUserPrn

func ValidateUserPrn(prn string) (bool, error)

ValidateUserPrn : Validate User Prn

func VerifyReCaptchaToken

func VerifyReCaptchaToken(token string) (bool, error)

VerifyReCaptchaToken validate a recaptcha token with google recaptcha API

Types

type AccessLogFluentMiddleware

type AccessLogFluentMiddleware struct {
	Logger    *fluent.Fluent
	Prefix    string
	Tag       string
	Namespace string
	Hostname  string
}

AccessLogFluentMiddleware produces the access log with records written as JSON. This middleware depends on TimerMiddleware and RecorderMiddleware that must be in the wrapped middlewares. It also uses request.Env["REMOTE_USER"].(string) set by the auth middlewares.

func (*AccessLogFluentMiddleware) MiddlewareFunc

MiddlewareFunc makes AccessLogJsonMiddleware implement the Middleware interface.

type AccessLogFluentRecord

type AccessLogFluentRecord struct {
	Endpoint       string
	Hostname       string
	HTTPMethod     string
	Namespace      string
	RemoteUser     string
	RequestHeaders map[string]interface{}
	RequestBody    string
	RequestParams  map[string]interface{}
	RequestURI     string
	ResponseBody   string
	ResponseSize   uint64
	ResponseTime   int64
	StatusCode     int
	Timestamp      int64
	UserAgent      string
}

AccessLogFluentRecord is the data structure used by AccessLogFluentMiddleware to create the JSON records. (Public for documentation only, no public method uses it)

type AuthInfo

type AuthInfo struct {
	Caller     Prn
	CallerType string
	Owner      Prn
	Roles      string
	Audience   string
	Scopes     []string
	Nick       string
	RemoteUser string
}

AuthInfo authentication information

func GetAuthInfo

func GetAuthInfo(r *rest.Request) *AuthInfo

GetAuthInfo get authentication information from a request

type AuthMiddleware

type AuthMiddleware struct{}

AuthMiddleware authentication default middleware

func (*AuthMiddleware) MiddlewareFunc

func (s *AuthMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc

MiddlewareFunc authentication middleware function

type CanonicalJSONMiddleware

type CanonicalJSONMiddleware struct{}

func (*CanonicalJSONMiddleware) MiddlewareFunc

MiddlewareFunc makes RecorderMiddleware implement the Middleware interface. Inspired by IndentJSONMiddleware by go-json-rest

type IScopes

type IScopes struct {
	API           Scope
	Profile       Scope
	ReadProfile   Scope
	ReadUser      Scope
	WriteUser     Scope
	Devices       Scope
	ReadDevices   Scope
	WriteDevices  Scope
	UpdateDevices Scope
	Objects       Scope
	ReadObjects   Scope
	WriteObjects  Scope
	UpdateObjects Scope
	Trails        Scope
	ReadTrails    Scope
	WriteTrails   Scope
	UpdateTrails  Scope
	Metrics       Scope
	ReadMetrics   Scope
	WriteMetrics  Scope
	UpdateMetrics Scope
}

IScopes define every possible scope type

type JSONLog

type JSONLog struct {
	Log    string    `json:"log"`
	Stream string    `json:"stream"`
	Time   time.Time `json:"time"`
}

JSONLog json payload for logs

type JwtRsaKeys

type JwtRsaKeys struct {
	PrivateKey *rsa.PrivateKey
	PublicKey  *rsa.PublicKey
}

JwtRsaKeys Public and Private keys for Jwt

func GetJwtRsaKeys

func GetJwtRsaKeys(secret, public string) (*JwtRsaKeys, error)

GetJwtRsaKeys return an JwtRsaKeys struct with public and private key

type Method

type Method string

Method define methods for encrypt supported

const (
	// BCryptMethod method
	BCryptMethod Method = "bcrypt"
	// SCryptMethod method
	SCryptMethod Method = "scrypt"
)

type PantahubDevicesJoinToken

type PantahubDevicesJoinToken struct {
	ID              primitive.ObjectID     `json:"id" bson:"_id"`
	Prn             string                 `json:"prn"`
	Nick            string                 `json:"nick"`
	Owner           string                 `json:"owner"`
	Token           string                 `json:"token,omitempty"`
	TokenSha        []byte                 `json:"token-sha,omitempty"`
	DefaultUserMeta map[string]interface{} `json:"default-user-meta"`
	Disabled        bool                   `json:"disabled"`
	TimeCreated     time.Time              `json:"time-created"`
	TimeModified    time.Time              `json:"time-modified"`
}

PantahubDevicesJoinToken devices join token payload

type Prn

type Prn string

Prn string to define Prn

func GetAdmins

func GetAdmins() []Prn

GetAdmins parses PANTAHUB_ADMINS env configuration and returns a list of Prns for users that shoudl have global admin powers

func GetSubscriptionAdmins

func GetSubscriptionAdmins() []Prn

GetSubscriptionAdmins parses PANTAHUB_SUBSCRIPTION ADMINS env configuration and returns a list of Prns for users that should have admin powers for processing subscription requsts

func (*Prn) GetInfo

func (p *Prn) GetInfo() (*PrnInfo, error)

GetInfo get information

type PrnInfo

type PrnInfo struct {
	Domain   string
	Service  string
	Resource string
}

PrnInfo Prn information

func (*PrnInfo) Equals

func (p *PrnInfo) Equals(c *PrnInfo) bool

Equals test if two PRN are equals

type PrnParseError

type PrnParseError string

PrnParseError string to define Prn parse Error

func (PrnParseError) Error

func (s PrnParseError) Error() string

type RError

type RError struct {
	IncidentID *int64 `json:"incident,omitempty"`
	Error      string `json:"error"`
	Msg        string `json:"msg,omitempty"`
	Code       int    `json:"cod,omitemptye"`
}

RError rest error struct

type ResponseWriterFunc

type ResponseWriterFunc func(string, rest.Request)

ResponseWriterFunc rest http writer func

type ResponseWriterWrapper

type ResponseWriterWrapper struct {
	RequestBody  []byte
	ResponseBody []byte
	// contains filtered or unexported fields
}

ResponseWriterWrapper response writer wrapper for rest

func NewResponseWriterWrapper

func NewResponseWriterWrapper(w rest.ResponseWriter) *ResponseWriterWrapper

NewResponseWriterWrapper create a new wrapper for writer

func (*ResponseWriterWrapper) Count

func (r *ResponseWriterWrapper) Count() uint64

Count count length of writer

func (*ResponseWriterWrapper) EncodeJson

func (r *ResponseWriterWrapper) EncodeJson(v interface{}) ([]byte, error)

EncodeJson encode json using a interface

func (*ResponseWriterWrapper) Header

func (r *ResponseWriterWrapper) Header() http.Header

Header get writer header

func (*ResponseWriterWrapper) Write

func (r *ResponseWriterWrapper) Write(c []byte) (int, error)

func (*ResponseWriterWrapper) WriteHeader

func (r *ResponseWriterWrapper) WriteHeader(code int)

WriteHeader write a header code

func (*ResponseWriterWrapper) WriteJson

func (r *ResponseWriterWrapper) WriteJson(v interface{}) error

WriteJson write a json response

type Scope

type Scope struct {
	ID          string `json:"id" bson:"id"`
	Service     string `json:"service" bson:"service"`
	Description string `json:"description" bson:"description"`
	Required    bool   `json:"required" bson:"required"`
}

Scope scope structure

func ScopeFilterBy

func ScopeFilterBy(scopes []Scope, f func(scope *Scope, i int) bool) []Scope

ScopeFilterBy filter and array of scopes using a function

type ScopeFilterMiddleware

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

func InitScopeFilterMiddleware

func InitScopeFilterMiddleware(filterTypes []Scope) *ScopeFilterMiddleware

func (*ScopeFilterMiddleware) MiddlewareFunc

func (m *ScopeFilterMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc

type URLCleanMiddleware

type URLCleanMiddleware struct{}

URLCleanMiddleware keeps a record of the HTTP status code of the response, and the number of bytes written. The result is available to the wrapping handlers as request.Env["STATUS_CODE"].(int), and as request.Env["BYTES_WRITTEN"].(int64)

func (*URLCleanMiddleware) MiddlewareFunc

func (mw *URLCleanMiddleware) MiddlewareFunc(h rest.HandlerFunc) rest.HandlerFunc

MiddlewareFunc makes RecorderMiddleware implement the Middleware interface.

type UserError

type UserError struct {
	Msg string
}

UserError user error type

func UserErrorNew

func UserErrorNew(msg string) *UserError

UserErrorNew user error factory

func (*UserError) Error

func (userError *UserError) Error() string

type UserTypeFilterMiddleware

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

func InitUserTypeFilterMiddleware

func InitUserTypeFilterMiddleware(filterTypes []accounts.AccountType) *UserTypeFilterMiddleware

func (*UserTypeFilterMiddleware) MiddlewareFunc

func (m *UserTypeFilterMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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