so://phie

verbal

A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal

blob: 640b397b30dbd93c88b2cf3cb31909dfb1beac59 (2689 bytes)[doc][blame][raw]

1use sqlx::postgres::Postgres;

2use sqlx::Acquire;

3use tide::http::Method;

4use tide_sqlx::SQLxRequestExt;

5

6use crate::model;

7use crate::unwrap_option_or_throw;

8use crate::unwrap_result_or_throw;

9use crate::Response;

10

11#[derive(Default)]

12pub struct Auth;

13

14#[tide::utils::async_trait]

15impl<State: Clone + Send + Sync + 'static> tide::Middleware<State> for Auth {

16 async fn handle(

17 &self,

18 mut req: tide::Request<State>,

19 next: tide::Next<'_, State>,

20 ) -> tide::Result {

21 let path_url = req.url().path();

22 if path_url.starts_with("/api") {

23 match req.header("verbal-token") {

24 Some(header) => {

25 let token = header.as_str();

26 let option_account;

27 {

28 let query = format!(

29 "

30 SELECT

31 account.*,

32 (

33 SELECT

34 sum(playtime)

35 FROM get_playtime(account.id)

36 )

37 AS playtime

38 FROM account

39 INNER JOIN device

40 ON account.id = device.account_id

41 WHERE device.uid = '{}'

42 ",

43 &token,

44 );

45 let mut conn = req.sqlx_conn::<Postgres>().await;

46 option_account = unwrap_result_or_throw!(

47 sqlx::query_as::<_, model::Account>(&query)

48 .fetch_optional(unwrap_result_or_throw!(

49 conn.acquire().await,

50 "cannot acquire connection to database!"

51 ))

52 .await,

53 "cannot acquire account for given device!"

54 );

55 }

56 req.set_ext(unwrap_option_or_throw!(

57 option_account,

58 "no account found for given token!"

59 ));

60 }

61 None => {

62 if !(path_url.eq("/api/account") && req.method() == Method::Post) {

63 return Response::throw("no token was provided!");

64 }

65 }

66 }

67 }

68 let res = next.run(req).await;

69 Ok(res)

70 }

71}