itpg

package module
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: May 23, 2024 License: GPL-3.0 Imports: 25 Imported by: 0

README

Is This Professor Good ? - Backend (itpg-backend)

Backend for itpg, which is a platform where students can grade their professors after taking courses. This permits future students to make more informed decisions when choosing their courses. This repository handles http requests, database transactions, and user state management.

Installation

Go install

$ go install github.com/vanillaiice/itpg/cmd/itpg@latest

Docker

$ docker pull vanillaiice/itpg:latest

Usage

NAME:
   itpg-backend - Backend server for ITPG, handles database transactions and user state management through HTTP(S) requests.

USAGE:
   itpg-backend [global options] command [command options]

VERSION:
   v0.4.3

AUTHOR:
   vanillaiice <[email protected]>

COMMANDS:
   help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --port PORT, -p PORT                                                               listen on PORT (default: "443")
   --db-backend value, -b value                                                       database backend, either sqlite or postgres (default: "sqlite")
   --db URL, -d URL                                                                   database connection URL (default: "itpg.db")
   --users-db value, -u value                                                         user state management bolt database (default: "users.db")
   --log-level value, -g value                                                        log level (default: "info")
   --cookie-timeout value, -i value                                                   cookie timeout in minutes (default: 30)
   --env FILE, -e FILE                                                                load SMTP configuration from FILE (default: ".env")
   --pass-reset-url URL, -r URL                                                       password reset web page URL
   --allowed-origins value, -o value [ --allowed-origins value, -o value ]            only allow specified origins to access resources (default: "*")
   --allowed-mail-domains value, -m value [ --allowed-mail-domains value, -m value ]  only allow specified mail domains to register (default: "*")
   --smtp, -s                                                                         use SMTP instead of SMTPS (default: false)
   --http, -t                                                                         use HTTP instead of HTTPS (default: false)
   --cert-file FILE, -c FILE                                                          load SSL certificate file from FILE
   --key-file FILE, -k FILE                                                           laod SSL secret key from FILE
   --load FILE, -l FILE                                                               load TOML config from FILE
   --help, -h                                                                         show help
   --version, -v                                                                      print the version

Examples

Using Go

If itpg was installed using go install, you can simply run it from the command line.

However, there should be an .env file containing the SMTP credentials needed to send confirmation emails.

# run the server with HTTP and pass an env file
$ itpg -t -e .smtp-env

# run the server with a TOML config file
$ itpg -l config.toml

Using Docker

# run the server with HTTPS and pass a TOML config file
$ ls itpg-data
# output: server.crt cert.key config.toml
$ docker run --rm -v ${PWD}/itpg-data:/itpg-data vanillaiice/itpg --load itpg-data/config.toml

Author

Vanillaiice

Licence

GPLv3

Documentation

Index

Constants

View Source
const CodeLength = 8

CodeLength is the length of generated confirmation or reset code. The code is truncated from the beginning v4 uuid.

View Source
const ConfirmationCodeValidityTime = time.Hour * 3

ConfirmationCodeValidityTime is the time during which the confimatoin code is valid.

View Source
const CookieExpiryUserStateKey = "cookie-expiry"

CookieExpiryUserStateKey is the key in the Userstate database use to retrieve the expiry time of a session cookie.

View Source
const KeyConfirmationCodeValidityTime = "cc_validity"

KeyConfirmationCodeValidityTime is the key for geting the confirmation code validity time.

View Source
const MinPasswordScore = 3

MinPasswordScore is the minimum acceptable score of a password computed by zxcvbn.

View Source
const UsernameContextKey = "username"

UsernameContextKey is the key in the request's context to set the username for use in subsequent middleware.

Variables

View Source
var (
	// MailSendFunc is the function used to send mails.
	SendMailFunc func(mailToAddress string, message []byte) error
	// SMTPHost is the host used for SMTP communication.
	SMTPHost string
	// SMTPPort is the port number used for SMTP communication.
	SMTPPort string
	// SMTPURL is the full URL of the SMTP server, including the protocol and any additional path.
	SMTPURL string
	// MailFromAddress is the email address used as the sender in outgoing emails.
	MailFromAddress string
	// Username is the username used for authentication with the SMTP server.
	Username string
	// Password is the password used for authentication with the SMTP server.
	Password string
)

SMTP server configuration details

View Source
var AllowedMailDomains []string

AllowedMailDomains are the email domains allowed to register. If the first item of the slice is "*", all domains will be allowed.

View Source
var CookieTimeout time.Duration

CookieTimeout represents the duration after which a session cookie expires.

View Source
var DataDB db.DB

DataDB represents a database connection, storing professor names, course codes and names, and professor scores.

View Source
var LimitHandlerFunc = httprate.WithLimitHandler(func(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusTooManyRequests)
	responses.ErrRequestLimitReached.WriteJSON(w)
})

LimitHandlerFunc is executed when the request limit is reached.

LimiterLenient is a limiter that allows 1000 requests per second per IP.

LimiterModerate is a limiter that allows 1000 requests per minute per IP.

LimiterStrict is a limiter that allows 500 requests per hour per IP.

LimiterVeryStrict is a limiter that allows 100 requests per hour per IP.

View Source
var Logger = log.Logger

Logger is the logger used by the server.

View Source
var PasswordResetWebsiteURL string

PasswordResetURL is the URL of the password reset web page. An example URL would be: https://demo.itpg.cc/changepass. The backend server will then append the following to the previous URL: ?code=foobarbaz, and send it to the user's email. Then, the website should get the email and new password of the user, and make the following example POST request to the api server: curl https://api.itpg.cc/resetpass -d '{"code": "foobarbaz", "email": "[email protected]", "password": "fizzbuzz"}'

UserState stores the state of all users.

Functions

func AddCourse

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

AddCourse handles the HTTP request to add a new course.

func AddCourseProfessor added in v0.4.0

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

AddCourseProfessor handles the HTTP request to associate a course with a professor.

func AddProfessor

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

AddProfessor handles the HTTP request to add a new professor.

func ChangePassword

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

ChangePassword changes the account password of a currently logged-in user.

func ClearCookie

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

ClearCookie clears the cookie for the current user session.

func Confirm

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

Confirm confirms the user registration with the provided confirmation code.

func DeleteAccount

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

DeleteAccount deletes the account of the currently logged-in user.

func DummyMiddleware

func DummyMiddleware(next http.HandlerFunc) http.HandlerFunc

DummyMiddleware is middleware that does nothing. It is used to wrap the go-chi/httprate limiter around a handler

func GetCoursesByProfessorUUID

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

GetCoursesByProfessor handles the HTTP request to get courses associated with a professor.

func GetLastCourses

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

GetLastCourses handles the HTTP request to get all courses.

func GetLastProfessors

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

GetLastProfessors handles the HTTP request to get all professors.

func GetLastScores

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

GetLastScores handles the HTTP request to get all scores.

func GetProfessorsByCourseCode

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

GetProfessorsByCourse handles the HTTP request to get professors associated with a course.

func GetScoresByCourseCode

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

GetScoresByCourseCode handles the HTTP request to get scores associated with a course.

func GetScoresByCourseCodeLike

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

GetScoresByCourseCodeLike handles the HTTP request to get scores associated with a course.

func GetScoresByCourseName

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

GetScoresByCourseName handles the HTTP request to get scores associated with a course.

func GetScoresByCourseNameLike

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

GetScoresByCourseNameLike handles the HTTP request to get scores associated with a course.

func GetScoresByProfessorName

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

GetScoresByProfessorName handles the HTTP request to get scores associated with a professor's name.

func GetScoresByProfessorNameLike

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

GetScoresByProfessorNameLike handles the HTTP request to get scores associated with a professor's name.

func GetScoresByProfessorUUID

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

GetScoresByProfessorUUID handles the HTTP request to get scores associated with a professor.

func GradeCourseProfessor

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

GradeCourseProfessor handles the HTTP request to grade a professor for a specific course.

func InitCredsSMTP

func InitCredsSMTP(envPath string, SMTPS bool) (err error)

InitCredsSMTP initializes SMTP credentials from the environment variables defined in the provided .env file path.

func Login

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

Login handles user login by checking credentials, confirming registration, setting a cookie with an expiry time, and logging the user in.

func Logout

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

Logout logs out the currently logged-in user by removing their session.

func Ping

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

Ping checks that the user is logged in and that the cookie is not expired.

func RefreshCookie

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

RefreshCookie refreshes the cookie for the current user session by updating its expiry time.

func Register

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

Register handles user registration by validating credentials, generating a confirmation code, sending an email with the code, and adding the user to the system.

func RemoveCourse

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

RemoveCourse handles the HTTP request to remove a course.

func RemoveCourseForce

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

RemoveCourseForce handles the HTTP request to forcefully remove a course.

func RemoveProfessor

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

RemoveProfessor handles the HTTP request to remove a professor.

func RemoveProfessorForce

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

RemoveProfessorForce handles the HTTP request to forcefully remove a professor.

func ResetPassword

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

ResetPassword resets the account password of a user, in case it was forgotten.

func Run

func Run(config *RunConfig) (err error)

Run starts the HTTP server on the specified port and connects to the specified database.

func SendMailSMTP

func SendMailSMTP(mailToAddress string, message []byte) error

SendMailSMTP sends an email using SMTP without authentication. This should only be used when the SMTP server and the itpg-backend binary are running on the same machine.

func SendMailSMTPS

func SendMailSMTPS(mailToAddress string, message []byte) error

SendMailSMTPS sends an email using SMTP over TLS, with SMTP authentication.

func SendNewConfirmationCode

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

SendNewConfirmationCode sends a new confirmation code to a registered user's email for confirmation.

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

SendResetLink sends a mail containing a password reset link

Types

type Credentials

type Credentials struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

Credentials represents the user credentials.

type CredentialsChange

type CredentialsChange struct {
	OldPassword string `json:"old"`
	NewPassword string `json:"new"`
}

CredentialsChange represents the user credentials for changing passwords.

type CredentialsReset

type CredentialsReset struct {
	Code     string `json:"code"`
	Email    string `json:"email"`
	Password string `json:"password"`
}

CredentialsReset represents the user credentials for resetting password.

type DatabaseBackend

type DatabaseBackend string

DatabaseBackend is the type of database backend to use.

const (
	Sqlite   DatabaseBackend = "sqlite"
	Postgres DatabaseBackend = "postgres"
)

Enum for datbase backend

type GradeData

type GradeData struct {
	CourseCode      string  `json:"code"`
	ProfUUID        string  `json:"uuid"`
	GradeTeaching   float32 `json:"teaching"`
	GradeCoursework float32 `json:"coursework"`
	GradeLearning   float32 `json:"learning"`
}

GradeData contains data needed to grade a course.

type HandlerInfo

type HandlerInfo struct {
	Path     string                                   // Path specifies the URL pattern for which the handler is responsible.
	Handler  func(http.ResponseWriter, *http.Request) // Handler is the function that will be called to handle HTTP requests.
	Method   string                                   // Method specifies the HTTP method associated with the handler.
	PathType PathType                                 // PathType is the type of the path (admin, user, public).
	Limiter  func(http.Handler) http.Handler          // Limiter is the limiter used to limit requests.
}

HandlerInfo represents a struct containing information about an HTTP handler.

type LogLevel added in v0.4.2

type LogLevel string

LogLevel is the log level to use.

const (
	LogLevelDisabled LogLevel = "disabled"
	LogLevelInfo     LogLevel = "info"
	LogLevelError    LogLevel = "error"
	LogLevelFatal    LogLevel = "fatal"
)

Enum for log levels.

type PathType

type PathType int

PathType is the type of the path (admin, user, public).

const (
	UserPath   PathType = 0 // UserPath is a path only accessible by users.
	PublicPath PathType = 1 // PublicPath is a path accessible by anyone.
	AdminPath  PathType = 2 // AdminPath is a path accessible by admins.
)

Enum for path types

type RunConfig

type RunConfig struct {
	Port                    string          // Port on which the server will run.
	DbURL                   string          // Path to the SQLite database file.
	DbBackend               DatabaseBackend // Database backend type.
	LogLevel                LogLevel        // Log level.
	UsersDBPath             string          // Path to the users BOLT database file.
	SMTPEnvPath             string          // Path to the .env file containing SMTP configuration.
	PasswordResetWebsiteURL string          // URL to the password reset website page.
	AllowedOrigins          []string        // List of allowed origins for CORS.
	AllowedMailDomains      []string        // List of allowed mail domains for registering with the service.
	UseSMTP                 bool            // Whether to use SMTP (false for SMTPS).
	UseHTTP                 bool            // Whether to use HTTP (false for HTTPS).
	CertFilePath            string          // Path to the certificate file (required for HTTPS).
	KeyFilePath             string          // Path to the key file (required for HTTPS).
	CookieTimeout           int             // Duration in minute after which a session cookie expires.
}

RunConfig defines the server's configuration settings.

Directories

Path Synopsis
cmd
db

Jump to

Keyboard shortcuts

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