2022-09-06 13:18:39 +03:00
module csrf
import rand
const chars = ' Q W E R T Z U I O P A S D F G H J K L Y X C V B N M q w e r t z u i o p a s d f g h j k l y x c v b n m 1 2 3 4 5 6 7 8 9 0 _ - '
const cookie_key = ' _ _ H o s t - C s r f - T o k e n '
2022-09-08 13:20:29 +03:00
// set_csrf_cookie - generates a CSRF-Token and sets the CSRF-Cookie. It is possible to set the HttpOnly-status of the cookie to false by adding an argument of the HttpOnly-struct like this:
2022-09-06 13:18:39 +03:00
// `app.set_csrf_cookie(csrf.HttpOnly{false})`
// If no argument is set, http_only will be set to `true`by default.
pub fn ( mut app App ) set_csrf_cookie ( h ... HttpOnly ) App {
mut http_only := true
if h . len > 0 {
http_only = h [ 0 ] . http_only
}
cookie := create_cookie ( http_only )
app = App { app . Context , cookie . value }
app . set_cookie ( cookie )
return app
}
// generate - generates the CSRF-Token
fn generate ( ) string {
mut out := ' '
for _ in 0 .. 42 {
i := rand . intn ( csrf . chars . len_utf8 ( ) ) or {
panic ( ' E r r o r w h i l e t r y i n g t o g e n e r a t e C s r f - T o k e n : $ err ' )
}
out = out + csrf . chars [ i .. i + 1 ]
}
return out
}
// create_cookie - creates the cookie
fn create_cookie ( h bool ) CsrfCookie {
return CsrfCookie {
name : csrf . cookie_key
value : generate ( )
path : ' / '
max_age : 0
secure : true
http_only : h
}
}
2022-09-08 13:20:29 +03:00
// get_csrf_token - returns the CSRF-Token that has been set. Make sure that you set one by using `set_csrf_cookie()`. If it's value is empty or no cookie has been generated, the function will throw an error.
2022-09-06 13:18:39 +03:00
pub fn ( mut app App ) get_csrf_token ( ) ? string {
if app . csrf_cookie_value != ' ' {
return app . csrf_cookie_value
} else {
return IError ( CsrfError {
m : ' T h e C S R F - T o k e n - V a l u e i s e m p t y . P l e a s e c h e c k i f y o u h a v e s e t t e d a c o o k i e ! '
} )
}
}