aboutsummaryrefslogtreecommitdiff
path: root/lib/models/login.dart
blob: 6412921d80ef48cb79ba8b3bd2fd268404b1fe87 (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
import "package:http/http.dart" as http;
import "dart:convert";

import "package:openbills/models/user.dart";

enum LoginMethod { email, username }

extension LoginMethodString on LoginMethod {
  String get value {
    switch(this) {
      case LoginMethod.username:
        return "username";
      case LoginMethod.email:
        return "email";
    }
  }
}

class LoginRes {
  final User user;
  final String authToken;
  final String refreshToken;

  LoginRes({
    required this.user,
    required this.authToken,
    required this.refreshToken,
  });

  factory LoginRes.fromJson(Map<String, dynamic> json) {
    return LoginRes(
      user: User.fromJson(json["data"]),
      authToken: json["auth_token"],
      refreshToken: json["refresh_token"],
    );
  }
}

Future<LoginRes> userSignIn(String accountName, method, password) async {
  final res = await http.post(
      Uri.parse("https://openbills.vidhukant.com/api/auth/signin"),
      headers: <String, String> {
        "Content-Type": "application/json; charset=UTF-8",
      },
      body: jsonEncode(<String, String> {
        "AccountName": accountName,
        "Method": method,
        "Password": password,
      })
  );

  final json = jsonDecode(res.body);

  if (res.statusCode != 200) {
    switch(res.statusCode) {
      case 404:
        throw "This user does not exist";
      case 500:
        throw "Internal Server Error";
      default:
        throw json["error"];
    }
  }

  return LoginRes.fromJson(json);
}