# auth.rs - source
Source of the Rust file `src/api/v1/auth.rs`.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190

    // Copyright (C) 2022  Aravinth Manivannan <realaravinth@batsense.net>
    // SPDX-FileCopyrightText: 2023 Aravinth Manivannan <realaravinth@batsense.net>
    //
    // SPDX-License-Identifier: AGPL-3.0-or-later

    use actix_identity::Identity;
    use actix_web::http::header;
    use actix_web::{web, HttpResponse, Responder};
    use db_core::errors::DBError;
    use serde::{Deserialize, Serialize};

    use super::mcaptcha::get_random;
    use crate::errors::*;
    use crate::AppData;

    pub mod routes {
        use actix_auth_middleware::GetLoginRoute;

        pub struct Auth {
            pub logout: &'static str,
            pub login: &'static str,
            pub register: &'static str,
        }

        impl Auth {
            pub const fn new() -> Auth {
                let login = "/api/v1/signin";
                let logout = "/logout";
                let register = "/api/v1/signup";
                Auth {
                    logout,
                    login,
                    register,
                }
            }
        }

        impl GetLoginRoute for Auth {
            fn get_login_route(&self, src: Option<&str>) -> String {
                if let Some(redirect_to) = src {
                    format!(
                        "{}?redirect_to={}",
                        self.login,
                        urlencoding::encode(redirect_to)
                    )
                } else {
                    self.login.to_string()
                }
            }
        }
    }

    pub mod runners {
        use super::*;

        #[derive(Clone, Debug, Deserialize, Serialize)]
        pub struct Register {
            pub username: String,
            pub password: String,
            pub confirm_password: String,
            pub email: Option<String>,
        }

        #[derive(Clone, Debug, Deserialize, Serialize)]
        pub struct Login {
            // login accepts both username and email under "username field"
            // TODO update all instances where login is used
            pub login: String,
            pub password: String,
        }

        #[derive(Clone, Debug, Deserialize, Serialize)]
        pub struct Password {
            pub password: String,
        }

        /// returns Ok(()) when everything checks out and the user is authenticated. Errors otherwise
        pub async fn login_runner(payload: Login, data: &AppData) -> ServiceResult<String> {
            use argon2_creds::Config;

            let verify = |stored: &str, received: &str| {
                if Config::verify(stored, received)? {
                    Ok(())
                } else {
                    Err(ServiceError::WrongPassword)
                }
            };

            let s = if payload.login.contains('@') {
                data.db
                    .get_password(&db_core::Login::Email(&payload.login))
                    .await?
            } else {
                let username = data.creds.username(&payload.login)?;
                data.db
                    .get_password(&db_core::Login::Username(&username))
                    .await?
            };

            verify(&s.hash, &payload.password)?;
            Ok(s.username)
        }
        pub async fn register_runner(
            payload: &Register,
            data: &AppData,
        ) -> ServiceResult<()> {
            if !data.settings.allow_registration {
                return Err(ServiceError::ClosedForRegistration);
            }

            if payload.password != payload.confirm_password {
                return Err(ServiceError::PasswordsDontMatch);
            }
            let username = data.creds.username(&payload.username)?;
            let hash = data.creds.password(&payload.password)?;

            if let Some(email) = &payload.email {
                data.creds.email(email)?;
            }

            let mut secret;

            loop {
                secret = get_random(32);

                let p = db_core::Register {
                    username: &username,
                    hash: &hash,
                    email: payload.email.as_deref(),
                    secret: &secret,
                };

                match data.db.register(&p).await {
                    Ok(_) => break,
                    Err(DBError::SecretTaken) => continue,
                    Err(e) => return Err(e.into()),
                }
            }

            Ok(())
        }
    }

    pub fn services(cfg: &mut web::ServiceConfig) {
        cfg.service(register);
        cfg.service(login);
        cfg.service(signout);
    }
    #[my_codegen::post(path = "crate::V1_API_ROUTES.auth.register")]
    async fn register(
        payload: web::Json<runners::Register>,
        data: AppData,
    ) -> ServiceResult<impl Responder> {
        runners::register_runner(&payload, &data).await?;
        Ok(HttpResponse::Ok())
    }

    #[my_codegen::post(path = "crate::V1_API_ROUTES.auth.login")]
    async fn login(
        id: Identity,
        payload: web::Json<runners::Login>,
        query: web::Query<super::RedirectQuery>,
        data: AppData,
    ) -> ServiceResult<impl Responder> {
        let username = runners::login_runner(payload.into_inner(), &data).await?;
        id.remember(username);
        //    Ok(HttpResponse::Ok())

        let query = query.into_inner();
        if let Some(redirect_to) = query.redirect_to {
            Ok(HttpResponse::Found()
                .append_header((header::LOCATION, redirect_to))
                .finish())
        } else {
            Ok(HttpResponse::Ok().finish())
        }
    }

    #[my_codegen::get(
        path = "crate::V1_API_ROUTES.auth.logout",
        wrap = "crate::api::v1::get_middleware()"
    )]
    async fn signout(id: Identity) -> impl Responder {
        if id.identity().is_some() {
            id.forget();
        }
        HttpResponse::Found()
            .append_header((header::LOCATION, crate::PAGES.auth.login))
            .finish()
    }