Skip to content

Commit f85a0cc

Browse files
author
Leonid
committed
added two factor auth functionality for users
1 parent 53b9efe commit f85a0cc

File tree

13 files changed

+160
-73
lines changed

13 files changed

+160
-73
lines changed

eFormAPI/eFormAPI/Controllers/AdminController.cs

Lines changed: 4 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using eFormAPI.Web.Infrastructure.Consts;
1010
using eFormAPI.Web.Infrastructure.Data;
1111
using eFormAPI.Web.Infrastructure.Data.Entities;
12+
using eFormAPI.Web.Infrastructure.Helpers;
1213
using eFormAPI.Web.Infrastructure.Identity;
1314
using eFormAPI.Web.Infrastructure.Models.API;
1415
using eFormAPI.Web.Infrastructure.Models.Common;
@@ -177,18 +178,13 @@ public OperationResult CreateUser(UserRegisterModel userRegisterModel)
177178
{
178179
return new OperationResult(false, "Role is required");
179180
}
180-
var twoFactorEnabled = UserManager.Users.FirstOrDefault()?.TwoFactorEnabled;
181-
if (twoFactorEnabled == null)
182-
{
183-
twoFactorEnabled = false;
184-
}
185181
var user = new EformUser
186182
{
187183
Email = userRegisterModel.Email,
188184
UserName = userRegisterModel.UserName,
189185
FirstName = userRegisterModel.FirstName,
190186
LastName = userRegisterModel.LastName,
191-
TwoFactorEnabled = (bool) twoFactorEnabled,
187+
TwoFactorEnabled = false,
192188
IsGoogleAuthenticatorEnabled = false
193189
};
194190

@@ -242,18 +238,9 @@ public OperationResult DeleteUser(int userId)
242238
[Authorize(Roles = EformRoles.Admin)]
243239
public OperationResult EnableTwoFactorAuthForce()
244240
{
245-
var queryString = @"
246-
UPDATE Users
247-
SET TwoFactorEnabled = 1";
248241
try
249242
{
250-
using (var connection =
251-
new SqlConnection(_connectionString))
252-
{
253-
connection.Open();
254-
var command = new SqlCommand(queryString, connection);
255-
command.ExecuteNonQuery();
256-
}
243+
SettingsHelper.UpdateTwoFactorAuthForceInfo(true);
257244
}
258245
catch (Exception)
259246
{
@@ -267,18 +254,9 @@ UPDATE Users
267254
[Authorize(Roles = EformRoles.Admin)]
268255
public OperationResult DisableTwoFactorAuthForce()
269256
{
270-
var queryString = @"
271-
UPDATE Users
272-
SET TwoFactorEnabled = 0";
273257
try
274258
{
275-
using (var connection =
276-
new SqlConnection(_connectionString))
277-
{
278-
connection.Open();
279-
var command = new SqlCommand(queryString, connection);
280-
command.ExecuteNonQuery();
281-
}
259+
SettingsHelper.UpdateTwoFactorAuthForceInfo(false);
282260
}
283261
catch (Exception)
284262
{

eFormAPI/eFormAPI/Controllers/AuthController.cs

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
using System;
2-
using System.Linq;
32
using System.Net.Http;
43
using System.Web;
54
using System.Web.Http;
65
using Base32;
6+
using eFormAPI.Web.Infrastructure.Helpers;
77
using eFormAPI.Web.Infrastructure.Identity;
88
using eFormAPI.Web.Infrastructure.Models.API;
99
using eFormAPI.Web.Infrastructure.Models.Auth;
@@ -57,18 +57,12 @@ public OperationDataResult<bool> TwoFactorAuthForceInfo()
5757
{
5858
try
5959
{
60-
var user = UserManager.Users.FirstOrDefault();
61-
if (user != null)
62-
{
63-
var twoFactorEnabled = user.TwoFactorEnabled;
64-
return new OperationDataResult<bool>(true, twoFactorEnabled);
65-
}
60+
return new OperationDataResult<bool>(true, SettingsHelper.GetTwoFactorAuthForceInfo());
6661
}
6762
catch (Exception)
6863
{
6964
return new OperationDataResult<bool>(false);
7065
}
71-
return new OperationDataResult<bool>(false);
7266
}
7367

7468
[HttpGet]
@@ -82,7 +76,9 @@ public OperationDataResult<GoogleAuthInfoModel> GetGoogleAuthenticatorInfo()
8276
{
8377
var model = new GoogleAuthInfoModel()
8478
{
85-
PSK = user.GoogleAuthenticatorSecretKey
79+
PSK = user.GoogleAuthenticatorSecretKey,
80+
IsTwoFactorEnabled = user.TwoFactorEnabled,
81+
IsTwoFactorForced = SettingsHelper.GetTwoFactorAuthForceInfo()
8682
};
8783
return new OperationDataResult<GoogleAuthInfoModel>(true, model);
8884
}
@@ -94,6 +90,30 @@ public OperationDataResult<GoogleAuthInfoModel> GetGoogleAuthenticatorInfo()
9490
return new OperationDataResult<GoogleAuthInfoModel>(false);
9591
}
9692

93+
[HttpPost]
94+
[Route("api/auth/google-auth-info")]
95+
public OperationResult UpdateGoogleAuthenticatorInfo(GoogleAuthInfoModel requestModel)
96+
{
97+
try
98+
{
99+
var user = UserManager.FindById(User.Identity.GetUserId<int>());
100+
if (user != null)
101+
{
102+
user.TwoFactorEnabled = requestModel.IsTwoFactorEnabled;
103+
var updateResult = UserManager.UpdateAsync(user).Result;
104+
if (updateResult.Succeeded)
105+
{
106+
return new OperationResult(true);
107+
}
108+
}
109+
}
110+
catch (Exception)
111+
{
112+
return new OperationResult(false);
113+
}
114+
return new OperationResult(false);
115+
}
116+
97117
[HttpDelete]
98118
[Route("api/auth/google-auth-info")]
99119
public OperationResult DeleteGoogleAuthenticatorInfo()
@@ -140,6 +160,12 @@ public OperationDataResult<GoogleAuthenticatorModel> GetGoogleAuthenticator(Logi
140160
return new OperationDataResult<GoogleAuthenticatorModel>(false,
141161
"The user name or password is incorrect.");
142162
}
163+
// check if two factor is enabled
164+
var isTwoFactorAuthForced = SettingsHelper.GetTwoFactorAuthForceInfo();
165+
if (!user.TwoFactorEnabled && !isTwoFactorAuthForced)
166+
{
167+
return new OperationDataResult<GoogleAuthenticatorModel>(true);
168+
}
143169
// generate PSK and barcode
144170
if (!string.IsNullOrEmpty(user.GoogleAuthenticatorSecretKey) && user.IsGoogleAuthenticatorEnabled)
145171
{

eFormAPI/eFormAPI/Infrastructure/Helpers/SettingsHelper.cs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
1-
using System.Configuration;
1+
using System;
2+
using System.Configuration;
23
using System.Linq;
4+
using System.Web.Configuration;
35
using eFormAPI.Web.Infrastructure.Data;
46
using eFormAPI.Web.Infrastructure.Data.Entities;
57
using eFormAPI.Web.Infrastructure.Identity;
68
using eFormAPI.Web.Infrastructure.Models.Settings.Initial;
79
using Microsoft.AspNet.Identity;
10+
using NLog;
811

912
namespace eFormAPI.Web.Infrastructure.Helpers
1013
{
1114
public class SettingsHelper
1215
{
1316
private string _connectionString;
17+
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
1418

1519
public SettingsHelper(string connectionString)
1620
{
@@ -41,5 +45,37 @@ public void CreateAdminUser(AdminSetupModel adminSetupModel)
4145
manager.AddToRole(adminUser.Id, "admin");
4246
}
4347
}
48+
49+
public static bool GetTwoFactorAuthForceInfo()
50+
{
51+
try
52+
{
53+
54+
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
55+
var section = (AppSettingsSection)configuration.GetSection("appSettings");
56+
return section.Settings["auth:isTwoFactorForced"].Value.Equals("True");
57+
}
58+
catch (Exception e)
59+
{
60+
Logger.Error(e.Message);
61+
}
62+
return false;
63+
}
64+
65+
public static void UpdateTwoFactorAuthForceInfo(bool isTwoFactorEnabled)
66+
{
67+
try
68+
{
69+
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
70+
var section = (AppSettingsSection)configuration.GetSection("appSettings");
71+
section.Settings["auth:isTwoFactorForced"].Value = isTwoFactorEnabled.ToString();
72+
configuration.Save();
73+
ConfigurationManager.RefreshSection("appSettings");
74+
}
75+
catch (Exception e)
76+
{
77+
Logger.Error(e.Message);
78+
}
79+
}
4480
}
4581
}

eFormAPI/eFormAPI/Infrastructure/Identity/Providers/ApplicationOAuthProvider.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Threading.Tasks;
55
using Base32;
66
using eFormAPI.Web.Infrastructure.Data.Entities;
7+
using eFormAPI.Web.Infrastructure.Helpers;
78
using Microsoft.AspNet.Identity.Owin;
89
using Microsoft.Owin.Security;
910
using Microsoft.Owin.Security.Cookies;
@@ -36,7 +37,8 @@ public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwner
3637
var requestData = await context.Request.ReadFormAsync();
3738
var psk = user.GoogleAuthenticatorSecretKey;
3839
var code = requestData.Get("code");
39-
if (user.TwoFactorEnabled)
40+
var isTwoFactorAuthForced = SettingsHelper.GetTwoFactorAuthForceInfo();
41+
if (user.TwoFactorEnabled || isTwoFactorAuthForced)
4042
{
4143
// check input params
4244
if (string.IsNullOrEmpty(psk) || string.IsNullOrEmpty(code))

eFormAPI/eFormAPI/Infrastructure/Models/Auth/GoogleAuthInfoModel.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,7 @@
33
public class GoogleAuthInfoModel
44
{
55
public string PSK { get; set; }
6+
public bool IsTwoFactorEnabled { get; set; }
7+
public bool IsTwoFactorForced { get; set; }
68
}
79
}

eFormAPI/eFormAPI/Web.config

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
<add key="header:imageLinkVisible" value="True" />
3535
<add key="restore:securityCode" value="code" />
3636
<add key="restore:defaultPassword" value="Qq1234567$" />
37+
<add key="auth:isTwoFactorForced" value="False" />
3738
</appSettings>
3839
<!--
3940
For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.

eform-client/src/app/components/auth/auth.component.ts

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ export class AuthComponent implements OnInit {
2727
loginImage: any;
2828

2929
// Two factor
30-
twoFactorEnabled = false;
30+
twoFactorForced = false;
3131
showTwoFactorForm = false;
3232
googleAuthenticatorModel: GoogleAuthenticatorModel = new GoogleAuthenticatorModel;
3333

@@ -42,29 +42,34 @@ export class AuthComponent implements OnInit {
4242
private notifyService: NotifyService) {
4343
}
4444

45+
login() {
46+
this.authService.login(new LoginRequestModel(this.formLogin.getRawValue()))
47+
.subscribe((result: AuthResponseModel) => {
48+
localStorage.setItem('currentAuth', JSON.stringify(result));
49+
this.router.navigate(['/']).then();
50+
},
51+
(error) => {
52+
this.error = error;
53+
},
54+
);
55+
}
56+
4557
submitLoginForm(): void {
46-
if (this.twoFactorEnabled) {
4758
// send pre-request
4859
this.authService.loginAndGetGoogleAuthKey(new LoginRequestModel(this.formLogin.getRawValue()))
4960
.subscribe((result) => {
61+
if (result.success) {
62+
// check if two factor is enabled
5063
if (result.model) {
5164
this.googleAuthenticatorModel = result.model;
5265
this.showTwoFactorForm = true;
5366
} else {
54-
this.notifyService.error({text: '400 - Bad Request The user name or password is incorrect'});
67+
this.login();
5568
}
56-
});
57-
} else {
58-
this.authService.login(new LoginRequestModel(this.formLogin.getRawValue()))
59-
.subscribe((result: AuthResponseModel) => {
60-
localStorage.setItem('currentAuth', JSON.stringify(result));
61-
this.router.navigate(['/']).then();
62-
},
63-
(error) => {
64-
this.error = error;
65-
},
66-
);
67-
}
69+
} else {
70+
this.notifyService.error({text: '400 - Bad Request The user name or password is incorrect'});
71+
}
72+
});
6873
}
6974

7075
submitRestoreForm(): void {
@@ -166,7 +171,7 @@ export class AuthComponent implements OnInit {
166171

167172
getTwoFactorInfo() {
168173
this.authService.twoFactorAuthInfo().subscribe((data) => {
169-
this.twoFactorEnabled = data.model;
174+
this.twoFactorForced = data.model;
170175
});
171176
}
172177

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
11
export class GoogleAuthInfoModel {
22
psk: string;
3+
isTwoFactorEnabled: boolean;
4+
isTwoFactorForced: boolean;
5+
6+
constructor() {
7+
this.isTwoFactorForced = true;
8+
}
39
}

eform-client/src/app/modules/advanced/components/edit-entity-searchable-group/edit-entity-searchable-group.component.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,6 @@ export class EditEntitySearchableGroupComponent implements OnChanges {
109109

110110
addNewAdvEntitySearchableItem() {
111111
const item = new AdvEntitySearchableItemModel();
112-
debugger;
113112
item.entityItemUId = this.advEntitySearchableGroupEditModel.advEntitySearchableItemModels.length.toString();
114113
this.advEntitySearchableGroupEditModel.advEntitySearchableItemModels.push(item);
115114
}

eform-client/src/app/modules/settings/components/admin-settings/admin-settings.component.css

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,3 @@
4646
max-width: 225px;
4747
margin-bottom: 10px;
4848
}
49-

0 commit comments

Comments
 (0)