ocre-cli 0.2.0

Command-line tool for Ocre: create, generate, migrate, run and deploy apps.
//! Accounts at OAuth providers linked to users: the `identities` table.
//! Generated by `ocre g auth --oauth`.

use ocre::{Ctx, Result, params};
use serde::{Deserialize, Serialize};

use crate::models::user::User;

/// A row of the `identities` table.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Identity {
    pub id: i64,
    pub user_id: i64,
    /// `github`, `google`, ...
    pub provider: String,
    /// The user's id at the provider.
    pub uid: String,
    pub created_at: String,
}

/// The user linked to this account at `provider`.
pub async fn find_user(ctx: &Ctx, provider: &str, uid: &str) -> Result<Option<User>> {
    ctx.db()?
        .first(
            "SELECT users.* FROM identities JOIN users ON users.id = identities.user_id \
             WHERE identities.provider = ?1 AND identities.uid = ?2",
            params![provider, uid],
        )
        .await
}

/// Links the account at `provider` to `user_id` (once).
pub async fn link(ctx: &Ctx, user_id: i64, provider: &str, uid: &str) -> Result<()> {
    ctx.db()?
        .execute(
            "INSERT INTO identities (user_id, provider, uid) VALUES (?1, ?2, ?3) ON CONFLICT (provider, uid) DO NOTHING",
            params![user_id, provider, uid],
        )
        .await?;
    Ok(())
}

/// The accounts linked to a user.
pub async fn for_user(ctx: &Ctx, user_id: i64) -> Result<Vec<Identity>> {
    ctx.db()?.all("SELECT * FROM identities WHERE user_id = ?1 ORDER BY provider", params![user_id]).await
}