utils

package
v0.4.3-beta Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2024 License: GPL-3.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrWrongPassword = errors.New("Wrong password")
	ErrUserLockedOut = errors.New("User is locked out")

	// Init the panel users
	PanelUsers = InitPanelUsers(*Admins)
)

Functions

func DeleteAllCookies

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

DeleteAllCookies deletes the cookies in the following paths to be deleted. ["/", "/admin/login"]

func GenerateCSRF

func GenerateCSRF(sessionId string) (token string, err error)

GenerateCSRF generate CSRF tokens for state changing that needed to be guarded, using the given sessionId. Return error if the random number generation is failing or creating MAC hash is failing. Given sessionId should be in the form of base64.URLEncoding

full process: token => b64(HMAC(sessionId + "!" + b64(random_bytes), CsrfSecretBytes))+"."+(sessionId+"!"+b64(random_bytes)) simplify: token=b64(HMAC)+"."+(sessionId + "!" + b64(random_bytes))

func GenerateSessionId

func GenerateSessionId(n int) (string, error)

GererateSessionId generate CSPRN(cryptographically secure pseudo-random numbers) base on the given number of bytes and encode it into base64 to return a random, unique and url safe string. Returns error only if the internal CSPRNG is broken. example if n = 32 --> 42 byte, random string will return.

func GetMemoryUsage

func GetMemoryUsage() uint64

getMemoryUsage returns the memory usage in the current state of the function being called.

func HashPassword

func HashPassword(password string) (string, []byte, error)

HashPassword hashes the given password string to sha-256 hash returning the hashed values as a hex-dec value string and also in the form of byte slice.

func InitPanelUsers

func InitPanelUsers(string) map[string]string

InitPanelUsers returns the panel users map that each username maps to each password which is hashed already. Each user should be seperated by comma(,). Username and password of each user should be seperated by tilde(~).

func JSONRespond

func JSONRespond(w http.ResponseWriter, code int, data any)

JSONRespond responds the request with the given http status code and data. The given data will be marshal into JSON format.

func JSONRespondError

func JSONRespondError(w http.ResponseWriter, code int, msg string)

JSONRespondError responds with errors in JSON format using the given http.ResponseWriter, http status code and error message. This function doesn't allow to use the http.StatusOK for the code, and it'll panic if one try to use.

func RenderError

func RenderError(w http.ResponseWriter, message string, status int)

RenderError reders the apology template with the given status and return the parsed template as http response. `apology.html` file should be in the path `{project root}/web/templates/` to be able to work with this function.

func RenderParseTemplate

func RenderParseTemplate(w http.ResponseWriter, data any, filenames ...string)

RenderTemplate renders the given templates file names in the `{project root}/web/templates/` path. Return the parsed template as http response.

func RenderTemplate

func RenderTemplate(w http.ResponseWriter, templateName string, data interface{})

CAUTION: Before calling this function always ensure to provided the status code with w.WriteHeader(). RenderTemplate renders the preparsed templates with the given templateName and return the parsed template as http response. templateName should be the name of the preparsed template files that exists the '{project root}/web/templates/' path. You can find the available templateNames in the Templates.Temps map.

func RestartService

func RestartService() error

Function to restart V2Ray service

func SendNoti

func SendNoti(gotifyServer, appToken, title, message string, priority int) error

SendNoti sends the current situation to the gotify server.

func SessionSetPath

func SessionSetPath(w http.ResponseWriter, path string, sessionStore SessionStore) (*http.Cookie, string, error)

SessionSetPath sets a new session to the given response to be able to access the given path while also adding to the session store. Returns the session cookie that is being set and error if there's problem with creating random strings or session store related problem. CAUTION: for pattern matching for path parameter. if the path is suffixed with "/"(back-slash), the cookie will be sent to all the sub-paths under the prefix. e.g. "/login/" will match both "/login/60", andf"/login/page/" but not "/loginpage/" e.g. "/login" will exactly match with http path "/login"

func SessionSetPrivate

func SessionSetPrivate(w http.ResponseWriter, path string, sessionStore SessionStore) error

SessionSetPrivate sets the session to the given path while also adding to the sessionStore cache. Return error if there's problem with creating random session strings or sessionStore cache problem.

func SessionValidate

func SessionValidate(r *http.Request, sessionStore SessionStore) (string, func(http.ResponseWriter) error)

SessionValidate validates the session from the given request if there's any. Session id of the given request is valid(present in the cache) if return error is nil. CAUTION: type of the session is not validated as there are different type of sessions Returns the utils.DeleteAllCookies function if the session that the user has is invalid.

for e.g.(pre-session<public>, private<authenticated>)

Return the result(value) string(probably user id) that is stored inside dbRedis cache. If result string is "NaN", it is utils.SessionPublic

func ValidateConfig

func ValidateConfig() error

Function to validate V2Ray configuration

func VerifyCSRF

func VerifyCSRF(token string, r *http.Request) (bool, error)

VerifyCSRF verifies the CSRF token is valid or not using the request. The given csrf token is valid only if there's no error.

func VerifyPassword

func VerifyPassword(password string, correct string) (bool, error)

VerifyPassword verify the password Given with the correct Password. This method can be used to check the input password is the correct u's Password or not, while returning an error if there's any.

The password is a correct password, only if the boolean is "true", and error is "nil".

Types

type Client

type Client struct {
	Id         string `json:"id"`
	AlterId    int    `json:"alterId"`
	Username   string `json:"username"`
	DeviceId   string `json:"deviceId"`
	StartDate  string `json:"startDate"`
	ExpireDate string `json:"expireDate"`
}

Client is to store the user basic info in the seperate json data file.

type GotifyMessage

type GotifyMessage struct {
	Title    string `json:"title"`
	Message  string `json:"message"`
	Priority int    `json:"priority"`
}

Message data for the gotify server.

type Inbound

type Inbound struct {
	Port           int             `json:"port"`
	Listen         string          `json:"listen"`
	Protocol       string          `json:"protocol"`
	Settings       InboundSettings `json:"settings"`
	StreamSettings json.RawMessage `json:"streamSettings"` // Handles streamSettings dynamically
}

type InboundSettings

type InboundSettings struct {
	Clients []V2rayClient `json:"clients"`
}

type LockedOutRateLimiter

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

LockedOutRateLimiter manages login attempts and lockouts on usernames.

func NewLockedOutRateLimiter

func NewLockedOutRateLimiter() *LockedOutRateLimiter

NewRateLimiter initializes a new RateLimiter

func (*LockedOutRateLimiter) IsLockedOut

func (rl *LockedOutRateLimiter) IsLockedOut(username string) bool

IsLockedOut checks if a user is currently locked out

func (*LockedOutRateLimiter) RecordFailedAttempt

func (rl *LockedOutRateLimiter) RecordFailedAttempt(username string) error

RecordFailedAttempt increments the failed attempt count and locks out the user if necessary. Returns ErrUserLockedOut if the user is being locked out for too many failed attempts.

func (*LockedOutRateLimiter) ResetAttempts

func (rl *LockedOutRateLimiter) ResetAttempts(username string)

ResetAttempts resets the failed attempt count for a user

type LoginAttempt

type LoginAttempt struct {
	FailedCount int
	LockedUntil time.Time
}

LoginAttempt tracks failed login attempts and lockout status

type V2rayClient

type V2rayClient struct {
	Id      string `json:"id"`
	AlterId int    `json:"alterId"`
}

V2rayClient is to add or remove the users from the v2ray config.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳