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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*
* Copyright (C) 2021  Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

use actix_identity::Identity;
use actix_web::http::header;
use actix_web::{web, HttpResponse, Responder};
use serde::{Deserialize, Serialize};
//use futures::{future::TryFutureExt, join};

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

pub mod routes {
    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,
            }
        }
    }
}

pub mod runners {
    use std::borrow::Cow;

    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. Erros otherwise
    pub async fn login_runner(payload: Login, data: &AppData) -> ServiceResult<String> {
        use argon2_creds::Config;
        use sqlx::Error::RowNotFound;

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

        if payload.login.contains('@') {
            #[derive(Clone, Debug)]
            struct EmailLogin {
                name: String,
                password: String,
            }

            let email_fut = sqlx::query_as!(
                EmailLogin,
                r#"SELECT name, password  FROM mcaptcha_users WHERE email = ($1)"#,
                &payload.login,
            )
            .fetch_one(&data.db)
            .await;

            match email_fut {
                Ok(s) => {
                    verify(&s.password, &payload.password)?;
                    Ok(s.name)
                }

                Err(RowNotFound) => Err(ServiceError::AccountNotFound),
                Err(_) => Err(ServiceError::InternalServerError),
            }
        } else {
            let username_fut = sqlx::query_as!(
                Password,
                r#"SELECT password  FROM mcaptcha_users WHERE name = ($1)"#,
                &payload.login,
            )
            .fetch_one(&data.db)
            .await;

            match username_fut {
                Ok(s) => {
                    verify(&s.password, &payload.password)?;
                    Ok(payload.login)
                }
                Err(RowNotFound) => Err(ServiceError::AccountNotFound),
                Err(_) => Err(ServiceError::InternalServerError),
            }
        }
    }

    pub async fn register_runner(
        payload: &Register,
        data: &AppData,
    ) -> ServiceResult<()> {
        if !crate::SETTINGS.server.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 res;
            if let Some(email) = &payload.email {
                res = sqlx::query!(
                    "insert into mcaptcha_users 
        (name , password, email, secret) values ($1, $2, $3, $4)",
                    &username,
                    &hash,
                    &email,
                    &secret,
                )
                .execute(&data.db)
                .await;
            } else {
                res = sqlx::query!(
                    "INSERT INTO mcaptcha_users 
        (name , password,  secret) VALUES ($1, $2, $3)",
                    &username,
                    &hash,
                    &secret,
                )
                .execute(&data.db)
                .await;
            }
            if res.is_ok() {
                break;
            } else if let Err(sqlx::Error::Database(err)) = res {
                if err.code() == Some(Cow::from("23505")) {
                    let msg = err.message();
                    if msg.contains("mcaptcha_users_name_key") {
                        return Err(ServiceError::UsernameTaken);
                    } else if msg.contains("mcaptcha_users_email_key") {
                        return Err(ServiceError::EmailTaken);
                    } else if msg.contains("mcaptcha_users_secret_key") {
                        continue;
                    } else {
                        return Err(ServiceError::InternalServerError);
                    }
                } else {
                    return Err(sqlx::Error::Database(err).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>,
    data: AppData,
) -> ServiceResult<impl Responder> {
    let username = runners::login_runner(payload.into_inner(), &data).await?;
    id.remember(username);
    Ok(HttpResponse::Ok())
}

#[my_codegen::get(path = "crate::V1_API_ROUTES.auth.logout", wrap = "crate::CheckLogin")]
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()
}