AccountController.cs
5.94 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http;
using AIAHTML5.WebAPI.Models;
using AIAHTML5.WebAPI.ViewModels;
using JWT;
namespace AIAHTML5.WebAPI.Controllers
{
public class AccountController : ApiController
{
[AllowAnonymous]
[Route("api/signin")]
[HttpPost]
public HttpResponseMessage Login(LoginViewModel model)
{
var loginSuccess = false;
User userObj = new User();
userObj.Email = "amrita.vishnoi@ebix.com";
userObj.Id = 1;
HttpResponseMessage response = null;
if (ModelState.IsValid)
{
if (model.Email == userObj.Email && model.Password == "education")
{
loginSuccess = true;
}
else
{
loginSuccess = false;
}
if (loginSuccess)
{
object dbUser;
var token = CreateToken(userObj, out dbUser);
response = Request.CreateResponse(new { dbUser, token });
}
}
else
{
response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
return response;
}
//[AllowAnonymous]
//[Route("signup")]
//[HttpPost]
//public HttpResponseMessage Register(RegisterViewModel model)
//{
// HttpResponseMessage response;
// if (ModelState.IsValid)
// {
// var existingUser = db.Users.FirstOrDefault(u => u.Email == model.Email);
// if (existingUser != null)
// {
// return Request.CreateResponse(HttpStatusCode.BadRequest, "User already exist.");
// }
// //Create user and save to database
// //var user = CreateUser(model);
// object dbUser;
// //Create token
// var token = CreateToken(user, out dbUser);
// response = Request.CreateResponse(new { dbUser, token });
// }
// else
// {
// response = Request.CreateResponse(HttpStatusCode.BadRequest, new { success = false });
// }
// return response;
//}
/// <summary>
/// Create a Jwt with user information
/// </summary>
/// <param name="user"></param>
/// <param name="dbUser"></param>
/// <returns></returns>
private static string CreateToken(User user, out object dbUser)
{
var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var expiry = Math.Round((DateTime.UtcNow.AddHours(2) - unixEpoch).TotalSeconds);
var issuedAt = Math.Round((DateTime.UtcNow - unixEpoch).TotalSeconds);
var notBefore = Math.Round((DateTime.UtcNow.AddMonths(6) - unixEpoch).TotalSeconds);
var payload = new Dictionary<string, object>
{
{"email", user.Email},
{"userId", user.Id},
{"role", "Admin" },
{"sub", user.Id},
{"nbf", notBefore},
{"iat", issuedAt},
{"exp", expiry}
};
//var secret = ConfigurationManager.AppSettings.Get("jwtKey");
const string apikey = "secretKey";
var token = JsonWebToken.Encode(payload, apikey, JwtHashAlgorithm.HS256);
dbUser = new { user.Email, user.Id };
return token;
}
/// <summary>
/// Create a new user and saves it to the database
/// </summary>
/// <param name="registerDetails"></param>
/// <returns></returns>
//private User CreateUser(RegisterViewModel registerDetails)
//{
// var passwordSalt = CreateSalt();
// var user = new User
// {
// Salt = passwordSalt,
// Email = registerDetails.Email,
// PasswordHash = EncryptPassword(registerDetails.Password, passwordSalt)
// };
// var adminRole = db.Roles.FirstOrDefault(d => d.Name == "Admin");
// user.Roles.Add(new UserRole
// {
// User = user,
// Role = adminRole
// });
// db.Users.Add(user);
// db.SaveChanges();
// return user;
//}
/// <summary>
/// Creates a random salt to be used for encrypting a password
/// </summary>
/// <returns></returns>
public static string CreateSalt()
{
var data = new byte[0x10];
using (var cryptoServiceProvider = new RNGCryptoServiceProvider())
{
cryptoServiceProvider.GetBytes(data);
return Convert.ToBase64String(data);
}
}
/// <summary>
/// Encrypts a password using the given salt
/// </summary>
/// <param name="password"></param>
/// <param name="salt"></param>
/// <returns></returns>
public static string EncryptPassword(string password, string salt)
{
using (var sha256 = SHA256.Create())
{
var saltedPassword = string.Format("{0}{1}", salt, password);
var saltedPasswordAsBytes = Encoding.UTF8.GetBytes(saltedPassword);
return Convert.ToBase64String(sha256.ComputeHash(saltedPasswordAsBytes));
}
}
//protected override void Dispose(bool disposing)
//{
// if (disposing)
// {
// db.Dispose();
// }
// base.Dispose(disposing);
//}
}
}