summaryrefslogtreecommitdiff
path: root/src/db.rs
blob: 077c1654ff55121a8f6025655d9fc09b7d2fc289 (plain)
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
use crate::error::Error;
use crate::models;
use bcrypt;
use diesel::connection::Connection;
use diesel::dsl::exists;
use diesel::dsl::select;
use diesel::pg::PgConnection;
use diesel::ExpressionMethods;
use diesel::QueryDsl;
use diesel::RunQueryDsl;

pub const COST: u32 = 10;

pub fn create_config(conn: &PgConnection, config: &models::Config) -> Result<(), Error> {
    use crate::schema::config;

    conn.transaction(|| {
        diesel::delete(config::table).execute(conn)?;

        diesel::insert_into(config::table)
            .values(config)
            .execute(conn)?;
        Ok(())
    })
}

pub fn get_config(conn: &PgConnection) -> Result<models::Config, Error> {
    use crate::schema::config;
    config::table
        .get_result::<models::Config>(conn)
        .map_err(From::from)
}

pub fn adduser(conn: &PgConnection, username: &str, password: &str) -> Result<(), Error> {
    use crate::schema::users;

    let hashed = bcrypt::hash(password, COST)?;
    let rows = diesel::insert_into(users::table)
        .values(models::NewUser {
            username,
            password: &hashed,
        })
        .execute(conn)?;
    if rows != 1 {
        Err(Error::AlreadyExists)?;
    }
    Ok(())
}

pub fn authenticate(
    conn: &PgConnection,
    username: &str,
    typed_password: &str,
) -> Result<models::User, Error> {
    use crate::schema::users;

    let mut user = users::table
        .filter(users::username.eq(username))
        .get_result::<models::User>(conn)?;

    if bcrypt::verify(typed_password, &user.password)? {
        user.password = "".to_string();
        Ok(user)
    } else {
        Err(Error::NotFound)
    }
}

pub fn get_user(conn: &PgConnection, username: &str) -> Result<models::User, Error> {
    use crate::schema::users;

    let mut user = users::table
        .filter(users::username.eq(username))
        .get_result::<models::User>(conn)?;
    user.password = "".to_string();
    Ok(user)
}