-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathExtController.cs
More file actions
1775 lines (1622 loc) · 75.7 KB
/
ExtController.cs
File metadata and controls
1775 lines (1622 loc) · 75.7 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using ExpressBase.Common;
using ExpressBase.Common.Constants;
using ExpressBase.Common.Extensions;
using ExpressBase.Common.LocationNSolution;
using ExpressBase.Common.ServiceClients;
using ExpressBase.Common.Structures;
using ExpressBase.Objects.ServiceStack_Artifacts;
using ExpressBase.Web.BaseControllers;
using ExpressBase.Web.Models;
using ExpressBase.Web2.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Newtonsoft.Json;
using ServiceStack;
using ServiceStack.Auth;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using RouteAttribute = Microsoft.AspNetCore.Mvc.RouteAttribute;
using ExpressBase.Security;
using ExpressBase.Common.Security;
using ExpressBase.Objects;
using ExpressBase.Common.Helpers;
using Newtonsoft.Json.Linq;
namespace ExpressBase.Web.Controllers
{
[EnableCors("AllowSpecificOrigin")]
public class ExtController : EbBaseExtController
{
public const string RequestEmail = "reqEmail";
MyAuthenticateResponse myAuthResponse = null;
public ExtController(IServiceClient _client, IRedisClient _redis, IHttpContextAccessor _cxtacc, IEbMqClient _mqc, IEbAuthClient _auth) : base(_client, _redis, _cxtacc, _mqc, _auth) { }
//[HttpPost]
//[EnableCors("AllowSpecificOrigin")]
//public bool JoinBeta()
//{
// string Email = this.HttpContext.Request.Form["Email"];
// JoinbetaResponse f = this.ServiceClient.Post<JoinbetaResponse>(new JoinbetaReq { Email = Email });
// return f.Status;
//}
[HttpGet]
public IActionResult QuestionNaire(int id)
{
ViewBag.Sid = id;
return View();
}
public IActionResult chatmessagetest()
{
return View();
}
public IActionResult EmailVerifyStructure()
{
return View();
}
public IActionResult MailAlreadyVerified()
{
return View();
}
[HttpGet("Platform/OnBoarding")]
public IActionResult SignUp()
{
//ViewBag.FacebookSigninAppid = 149537802493867;
ViewBag.FacebookSigninAppid = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_FB_APP_ID);
ViewBag.GoogleSigninAppid = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_GOOGLE_CLIENT_ID);
return View();
}
//profile setup tenant
[HttpPost]
public async Task<CreateAccountResponse> BoardAsync(string email, string name, string country, string password, string token)
{
var grecap = false;
CreateAccountResponse res = new CreateAccountResponse();
Recaptcha cap = null;
try
{
cap = await RecaptchaResponse(Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RECAPTCHA_SECRET), token);
grecap = cap.Success;
}
catch (Exception e)
{
Console.WriteLine("RECAPTCHA EXCEPTION");
Console.WriteLine(e.Message);
TempData["ErrorMessage"] = "Recaptcha error, try again";
}
if (grecap == true)
{
try
{
UniqueRequestResponse result = this.ServiceClient.Post<UniqueRequestResponse>(new UniqueRequest { Email = email });
if (result.Unique)
{
res.IsEmailUniq = true;
string activationcode = Guid.NewGuid().ToString();
var pgurl = this.HttpContext.Request.Host;
var pgpath = this.HttpContext.Request.Path;
res = this.ServiceClient.Post<CreateAccountResponse>(new CreateAccountRequest
{
Name = name,
Password = password,
Country = country,
Email = email,
Account_type = null,
ActivationCode = activationcode,
PageUrl = pgurl.ToString(),
PagePath = pgpath.ToString()
});
if (res.Id > 0)
{
MyAuthenticateResponse authResponse = this.ServiceClient.Get<MyAuthenticateResponse>(new Authenticate
{
provider = CredentialsAuthProvider.Name,
UserName = email,
Password = (password + email).ToMD5Hash(),
Meta = new Dictionary<string, string> { { RoutingConstants.WC, RoutingConstants.TC }, { TokenConstants.CID, CoreConstants.EXPRESSBASE } },
//UseTokenCookie = true
});
if (authResponse != null)
{
CookieOptions options = new CookieOptions();
Response.Cookies.Append(RoutingConstants.BEARER_TOKEN, authResponse.BearerToken, options);
Response.Cookies.Append(RoutingConstants.REFRESH_TOKEN, authResponse.RefreshToken, options);
Response.Cookies.Append(TokenConstants.USERAUTHID, authResponse.User.AuthId, options);
this.ServiceClient.BearerToken = authResponse.BearerToken;
this.ServiceClient.RefreshToken = authResponse.RefreshToken;
}
}
}
else
{
res.IsEmailUniq = false;
}
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message + e.StackTrace);
}
}
return res;
}
public int EmailCheck(string email)
{
try
{
UniqueRequestResponse result = this.ServiceClient.Post<UniqueRequestResponse>(new UniqueRequest { Email = email });
if (result.Unique)
{
return 1;
}
else
{
return 0;
}
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message + e.StackTrace);
}
return 0;
}
[HttpGet("ForgotPassword")]
public IActionResult ForgotPassword()
{
ViewBag.message = TempData["Message"];
return View();
}
[HttpPost]
public async Task<int> ForgotPasswordAsync(string email, string token)
{
var grecap = false;
Recaptcha cap = null;
bool is_user = !(ViewBag.SolutionId == CoreConstants.EXPRESSBASE);
try
{
cap = await RecaptchaResponse(Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RECAPTCHA_SECRET), token);
grecap = cap.Success;
}
catch (Exception e)
{
Console.WriteLine("RECAPTCHA EXCEPTION");
Console.WriteLine(e.Message);
TempData["ErrorMessage"] = "Recaptcha error, try again";
}
if (grecap == true)
{
try
{
UniqueRequestResponse result = this.ServiceClient.Post<UniqueRequestResponse>(new UniqueRequest
{
Email = email,
IsUser = is_user,
iSolutionId = ViewBag.SolutionId
});
if (result.Unique || !result.HasPassword)
{
return 0;
}
else
{
string resetcode = Guid.NewGuid().ToString();
HostString pgurl = this.HttpContext.Request.Host;
PathString pgpath = this.HttpContext.Request.Path;
ForgotPasswordResponse res = this.ServiceClient.Post<ForgotPasswordResponse>(new ForgotPasswordRequest
{
Email = email,
Resetcode = resetcode,
PagePath = pgpath.ToString(),
PageUrl = pgurl.ToString(),
IsUser = is_user,
iSolutionId = ViewBag.SolutionId
});
if (res.VerifyStatus == true)
{
return 1;
}
else
{
return 2;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message + e.StackTrace);
return 0;
}
}
return 2;
}
[HttpGet("resetpassword")]
public IActionResult ResetPassword(string rep)
{
ViewBag.rep = rep;
return View();
}
[HttpPost]
public async Task<int> ResetPasswordAsync(string emcde, string tkn, string psw, string token)
{
bool grecap = false;
int stts = 0;
bool is_user = !(ViewBag.SolutionId == CoreConstants.EXPRESSBASE);
try
{
Recaptcha cap = await RecaptchaResponse(Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RECAPTCHA_SECRET), token);
grecap = cap.Success;
}
catch (Exception e)
{
Console.WriteLine("RECAPTCHA EXCEPTION");
Console.WriteLine(e.Message);
TempData["ErrorMessage"] = "Recaptcha error, try again";
}
try
{
if (grecap == true)
{
byte[] base64Encoded = System.Convert.FromBase64String(emcde);
string resetcd = System.Text.Encoding.UTF8.GetString(base64Encoded);
string[] resetcode = resetcd.Split(new Char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
ResetPasswordResponse sts = this.ServiceClient.Post<ResetPasswordResponse>(new ResetPasswordRequest
{
Resetcode = resetcode[1],
Email = resetcode[0],
Password = psw,
IsUser = is_user,
iSolutionId = ViewBag.SolutionId
});
if (sts.VerifyStatus == true)
{
stts = 1;
}
else
{
stts = 0;
}
}
return stts;
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message + e.StackTrace);
return 0;
}
}
private bool isAvailSolution()
{
bool IsAvail = false;
if (ViewBag.SolutionId != String.Empty && ViewBag.SolutionId != null)
{
IsAvail = isAvailInRedis();
//if (!IsAvail)
//{
// RefreshSolutionExtResponse res = this.MqClient.Post<RefreshSolutionExtResponse>(new RefreshSolutionExtRequest { SolnId = ViewBag.SolutionId });
// IsAvail = isAvailInRedis();
//}
}
return IsAvail;
}
public bool isAvailInRedis()
{
bool IsAvail = false;
IEnumerable<string> resp = this.Redis.GetKeysByPattern(string.Format(CoreConstants.SOLUTION_INTEGRATION_REDIS_KEY, ViewBag.SolutionId));
if (resp.Any() || (ViewBag.SolutionId == CoreConstants.ADMIN))
IsAvail = true;
return IsAvail;
}
private string GetDefaultHtmlPageRefId()
{
Eb_Solution s_obj = this.Redis.Get<Eb_Solution>(String.Format("solution_{0}", ViewBag.SolutionId));
if (!string.IsNullOrWhiteSpace(s_obj?.SolutionSettings?.DefaultHtmlPageRefid))
return s_obj.SolutionSettings.DefaultHtmlPageRefid;
return string.Empty;
}
public IActionResult UsrSignIn(bool Page = true, string browser = "")
{
if (isAvailSolution())
{
string sBToken = base.HttpContext.Request.Cookies[RoutingConstants.BEARER_TOKEN];
string sRToken = base.HttpContext.Request.Cookies[RoutingConstants.REFRESH_TOKEN];
bool IsInternal = false;
if (!String.IsNullOrEmpty(sBToken) || !String.IsNullOrEmpty(sRToken))
{
if (IsTokensValid(sRToken, sBToken, ExtSolutionId))
{
IsInternal = true;
if (WhichConsole == RoutingConstants.DC)
return Redirect(RoutingConstants.MYAPPLICATIONS);
else
return RedirectToAction("UserDashboard", "TenantUser");
}
}
if (!IsInternal)
{
if (Page && WhichConsole == RoutingConstants.UC)
{
string refId = GetDefaultHtmlPageRefId();
if (!string.IsNullOrWhiteSpace(refId))
{
EbHtmlPage view = this.Redis.Get<EbHtmlPage>(refId);
if (view != null)
return base.Content(view.Html, "text/html");
}
}
ViewBag.HasSignupForm = false;
if (!(WhichConsole == RoutingConstants.DC))
{
Eb_Solution solutionObj = GetSolutionObject(ViewBag.SolutionId);
if (solutionObj.SolutionSettings != null && solutionObj.SolutionSettings.SignupFormRefid != string.Empty)
{
ViewBag.HasSignupForm = true;
}
ViewBag.Is2fA = solutionObj.Is2faEnabled;
ViewBag.IsOtpSigninEnabled = solutionObj.IsOtpSigninEnabled;
ViewBag.IsEmailIntegrated = solutionObj.IsEmailIntegrated;
ViewBag.IsSmsIntegrated = solutionObj.IsSmsIntegrated;
}
}
string SsoUrl = Environment.GetEnvironmentVariable("SULEKHA-SSO-URL") ?? string.Empty;
if (!string.IsNullOrEmpty(SsoUrl))
{
string[] parts = SsoUrl.Split("~~");
string cuid = Math.Round(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds).ToString();
string hash = cuid + parts[1] + DateTime.UtcNow.ToString("dd-MM-yyyy") + parts[2];
hash = hash.ToSha256Hash();
SsoUrl = string.Format(parts[0], cuid, hash);
}
ViewBag.SsoUrl = SsoUrl;
ViewBag.ServiceUrl = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_SERVICESTACK_EXT_URL);
ViewBag.ErrorMsg = TempData["ErrorMessage"];
ViewBag.Email = TempData["Email"];
ViewBag.Title = UrlHelper.GetLoginPageDescription(ViewBag.HostValue);
ViewBag.AllowBrowser = browser.ToLower();
return View();
}
else
return Redirect("/StatusCode/404");
}
[HttpGet]
public IActionResult TenantSignIn(string continue_with)
{
ViewBag.FacebookSigninAppid = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_FB_APP_ID);
ViewBag.GoogleSigninAppid = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_GOOGLE_CLIENT_ID);
string sBToken = base.HttpContext.Request.Cookies[RoutingConstants.BEARER_TOKEN];
string sRToken = base.HttpContext.Request.Cookies[RoutingConstants.REFRESH_TOKEN];
if (!String.IsNullOrEmpty(sBToken) || !String.IsNullOrEmpty(sRToken))
{
if (IsTokensValid(sRToken, sBToken, ExtSolutionId))
return Redirect(RoutingConstants.MYSOLUTIONS);
}
ViewBag.ServiceUrl = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_SERVICESTACK_EXT_URL);
ViewBag.ErrorMsg = TempData["ErrorMessage"];
ViewBag.Email = TempData["Email"];
ViewBag.ContinueWith = continue_with;
return View();
}
public IActionResult FacebookLogin(string name, string fbid, string email)
{
Console.WriteLine("reached contoller / facebooklogin");
try
{
if ((email != null) & (fbid != null))
{
SocialLoginResponse res = this.ServiceClient.Post<SocialLoginResponse>(new SocialLoginRequest
{
Email = email,
Fbid = fbid,
Name = name,
});
Console.WriteLine("reached completed service to store user details SocialLoginRequest of facebook");
return SocialOath(res.jsonval);
}
}
catch (Exception e)
{
Console.WriteLine("reached exception FacebookLogin");
TempData["socloginerr"] = "Something went wrong. Please try later";
Console.WriteLine("Exception: " + e.Message + e.StackTrace);
return Redirect("/Platform/OnBoarding");
}
return Redirect("/Platform/OnBoarding");
}
public IActionResult GoogleLogin(string name, string goglid, string email)
{
Console.WriteLine("reached contoller / GoogleLogin");
try
{
if ((email != null) & (goglid != null))
{
SocialLoginResponse res = this.ServiceClient.Post<SocialLoginResponse>(new SocialLoginRequest
{
Email = email,
Goglid = goglid,
Name = name,
});
Console.WriteLine("reached completed service to store user details SocialLoginRequest of google");
return SocialOath(res.jsonval);
}
}
catch (Exception e)
{
Console.WriteLine("reached exception GoogleLogin");
TempData["socloginerr"] = "Something went wrong. Please try later";
Console.WriteLine("Exception: " + e.Message + e.StackTrace);
return Redirect("/Platform/OnBoarding");
}
return Redirect("/Platform/OnBoarding");
}
[HttpGet("social_oauth")]
public IActionResult SocialOath(string scosignup)
{
Console.WriteLine("reached contoller / SocialOath");
SocialSignup Social = JsonConvert.DeserializeObject<SocialSignup>(scosignup);
if (Social.UniqueEmail)
{
Console.WriteLine("reached UniqueEmail");
MyAuthenticateResponse authResponse = this.AuthClient.Get<MyAuthenticateResponse>(new Authenticate
{
provider = CredentialsAuthProvider.Name,
UserName = Social.Email,
Password = Social.Pauto,
Meta = new Dictionary<string, string> { { RoutingConstants.WC, RoutingConstants.TC }, { TokenConstants.CID, CoreConstants.EXPRESSBASE } },
//UseTokenCookie = true
});
if (authResponse != null)
{
CookieOptions options = new CookieOptions();
Response.Cookies.Append(RoutingConstants.BEARER_TOKEN, authResponse.BearerToken, options);
Response.Cookies.Append(RoutingConstants.REFRESH_TOKEN, authResponse.RefreshToken, options);
this.ServiceClient.BearerToken = authResponse.BearerToken;
this.ServiceClient.RefreshToken = authResponse.RefreshToken;
}
CreateSolutionResponse tmp = this.ServiceClient.Post<CreateSolutionResponse>(new CreateSolutionRequest
{
SolutionName = "My First solution",
Description = "This is my first solution",
DeployDB = true,
});
Console.WriteLine("reached completed CreateSolutionRequest");
return Redirect(RoutingConstants.MYSOLUTIONS);
}
else
if (!Social.Forsignup)
{
Console.WriteLine("reached Forsignup??");
if ((Social.FbId == "") & (Social.GithubId == "") & (Social.TwitterId == "") & (Social.GoogleId == ""))
{
TempData["scl_signin_msg"] = "You have already completed Sign up. Please Sign in using your Email";
}
else
{
Console.WriteLine("reached user autologin");
SocialAutoSignInResponse lgid = this.ServiceClient.Post<SocialAutoSignInResponse>(new SocialAutoSignInRequest
{
Email = Social.Email,
Social_id = Social.Social_id
});
if (string.IsNullOrEmpty(lgid.psw))
{
TempData["scl_signin_msg"] = "Something went wrong. Please try later";
}
else
{
MyAuthenticateResponse authResponse = null;
try
{
string tenantid = lgid.Id.ToString();
authResponse = AuthClient.Get<MyAuthenticateResponse>(new Authenticate
{
provider = CredentialsAuthProvider.Name,
UserName = Social.Email,
Password = lgid.psw,
Meta = new Dictionary<string, string> { { RoutingConstants.WC, RoutingConstants.TC }, { TokenConstants.CID, CoreConstants.EXPRESSBASE/* tenantid*/ } },
RememberMe = true
//UseTokenCookie = true
});
}
catch (WebServiceException wse)
{
Console.WriteLine("Exception:" + wse.ToString());
TempData["ErrorMessage"] = wse.Message;
return Redirect("/");
}
catch (Exception wse)
{
Console.WriteLine("Exception:" + wse.ToString());
TempData["ErrorMessage"] = wse.Message;
return Redirect("/");
}
if (authResponse != null && authResponse.ResponseStatus != null && authResponse.ResponseStatus.ErrorCode == "EbUnauthorized")
{
TempData["ErrorMessage"] = "EbUnauthorized";
return Redirect("/");
}
else //AUTH SUCCESS
{
CookieOptions options = new CookieOptions();
Response.Cookies.Append(RoutingConstants.BEARER_TOKEN, authResponse.BearerToken, options);
Response.Cookies.Append(RoutingConstants.REFRESH_TOKEN, authResponse.RefreshToken, options);
Response.Cookies.Append(TokenConstants.USERAUTHID, authResponse.User.AuthId, options);
Response.Cookies.Append("UserDisplayName", authResponse.User.FullName, options);
//if (req.ContainsKey("remember"))
// Response.Cookies.Append("UserName", req["uname"], options);
//_redirectUrl = this.RouteToDashboard(whichconsole);
}
}
Console.WriteLine("reached RoutingConstants.MYSOLUTIONS");
return Redirect(RoutingConstants.MYSOLUTIONS);
}
Console.WriteLine("reached RoutingConstants.TENANTSIGNIN");
return RedirectToAction(RoutingConstants.TENANTSIGNIN);
}
else
{
if (Social.AuthProvider == "github")
{
TempData["scl_signin_msg"] = "You have already created an accout with Github";
}
if (Social.AuthProvider == "facebook")
{
TempData["scl_signin_msg"] = "You have already created an accout with Facebook";
}
}
return RedirectToAction(RoutingConstants.TENANTSIGNIN);
}
[HttpPost]
public async Task<IActionResult> TenantExtSignup()
{
try
{
string reqEmail = this.HttpContext.Request.Form[TokenConstants.EMAIL];
TempData[RequestEmail] = reqEmail;
UniqueRequestResponse result = this.ServiceClient.Post<UniqueRequestResponse>(new UniqueRequest { Email = reqEmail });
if (result.Unique)
{
RegisterResponse res = this.ServiceClient.Post<RegisterResponse>(new RegisterRequest { Email = reqEmail, DisplayName = CoreConstants.EXPRESSBASE });
if (Convert.ToInt32(res.UserId) >= 0)
return RedirectToAction("EbOnBoarding", new { Email = reqEmail }); // convert get to post
}
else
{
TempData["Email"] = reqEmail;
if (result.HasPassword)
return RedirectToAction("TenantSignIn");
}
}
catch (WebServiceException e)
{
Console.WriteLine("Exception:" + e.ToString());
}
return View();
}
[HttpGet("em")]
public IActionResult EmailVerify(string emv)
{
var base64Encoded = System.Convert.FromBase64String(emv);
var emailcd = System.Text.Encoding.UTF8.GetString(base64Encoded);
string[] emcode = emailcd.Split(new Char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
var sts = this.ServiceClient.Post<EmailverifyResponse>(new EmailverifyRequest
{
ActvCode = emcode[1],
Id = emcode[0]
});
if (sts.VerifyStatus == true)
{ return View(); }
else
{
return RedirectToAction("MailAlreadyVerified");
}
}
public IActionResult SwitchContext()
{
Console.WriteLine("Inside Context Switch");
var req = this.HttpContext.Request.Form;
string btoken = req["Btoken"].ToString();
string rtoken = req["Rtoken"].ToString();
string console = req["WhichConsole"];
//string req_url = this.HttpContext.Request.Host.Value;
if (TenantSingleSignOn(btoken, rtoken, console))
{
//string Subdomain = this.HttpContext.Request.Host.Host.Replace(RoutingConstants.LIVEHOSTADDRESS, string.Empty).Replace(RoutingConstants.STAGEHOSTADDRESS, string.Empty).Replace(RoutingConstants.LOCALHOSTADDRESS, string.Empty);
//bool is_ourdomain = (req_url.Contains(RoutingConstants.LIVEHOSTADDRESS) || req_url.Contains(RoutingConstants.STAGEHOSTADDRESS) || req_url.Contains(RoutingConstants.LOCALHOSTADDRESS));
//if (console == RoutingConstants.UC && Subdomain.Contains(CharConstants.DOT))
//{
// return Response.Redirect(this.HttpContext.Request.Scheme + "://" + Subdomain + "/UserDashboard");
//}
if (console == RoutingConstants.DC)
return RedirectToAction("DevDashBoard", "Dev");
else if (console == RoutingConstants.UC)
return RedirectToAction("UserDashboard", "TenantUser");
}
return View();
}
public bool TenantSingleSignOn(string btoken, string rtoken, string wc)
{
var host = this.HttpContext.Request.Host;
string Subdomain = host.Host.Replace(RoutingConstants.LIVEHOSTADDRESS, string.Empty).Replace(RoutingConstants.STAGEHOSTADDRESS, string.Empty).Replace(RoutingConstants.LOCALHOSTADDRESS, string.Empty);
//string[] hostParts = host.Host.Split(CharConstants.DOT);
string whichconsole = wc;
string email = ValidateTokensAndGetUserName(btoken, rtoken);
if (string.IsNullOrEmpty(email))
return false;
this.DecideConsole(Subdomain, out whichconsole);
MyAuthenticateResponse authResponse = null;
try
{
var authClient = this.ServiceClient;
authResponse = authClient.Get<MyAuthenticateResponse>(new Authenticate
{
provider = CredentialsAuthProvider.Name,
UserName = email,
Password = "NIL",
Meta = new Dictionary<string, string> {
{ RoutingConstants.WC, whichconsole },
{ TokenConstants.CID, ViewBag.cid },
{ "sso", "true" },
{ TokenConstants.IP, this.RequestSourceIp},
{ RoutingConstants.USER_AGENT, this.UserAgent}
},
});
}
catch (WebServiceException wse) { Console.WriteLine("Exception:" + wse.ToString()); }
catch (Exception wse) { Console.WriteLine("Exception:" + wse.ToString()); }
if (authResponse != null)
{
if (authResponse.ResponseStatus != null && authResponse.ResponseStatus.ErrorCode == "EbUnauthorized") { }
else //AUTH SUCCESS
{
CookieOptions options = new CookieOptions();
Response.Cookies.Append(RoutingConstants.BEARER_TOKEN, authResponse.BearerToken, options);
Response.Cookies.Append(RoutingConstants.REFRESH_TOKEN, authResponse.RefreshToken, options);
Response.Cookies.Append(TokenConstants.USERAUTHID, authResponse.User.AuthId, options);
return true;
}
}
return false;
}
private static async Task<Recaptcha> RecaptchaResponse(string secret, string token)
{
string url = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, token);
var req = WebRequest.Create(url);
var r = await req.GetResponseAsync().ConfigureAwait(false);
var responseReader = new StreamReader(r.GetResponseStream());
var responseData = await responseReader.ReadToEndAsync();
var d = Newtonsoft.Json.JsonConvert.DeserializeObject<Recaptcha>(responseData);
return d;
}
private void EventLogWriteEntry()
{
var t = this.HttpContext.Request.Headers["Eb-X-Forwarded-For"];
Console.WriteLine("-------------------------------------------------");
IPHostEntry heserver = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ttt in heserver.AddressList)
Console.WriteLine("From IP AddressList ---> " + ttt.ToString());
Console.WriteLine("-------------------------------------------------");
Console.WriteLine(this.httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());
foreach (var zzz in this.HttpContext.Request.Headers)
Console.WriteLine("Key : " + zzz.Key + "Value : " + zzz.Value);
}
[HttpPost]
public async Task<EbAuthResponse> EbSignIn(int i)
{
EbAuthResponse authresp = new EbAuthResponse();
this.EventLogWriteEntry();
IFormCollection req = this.HttpContext.Request.Form;
string UserName;
string Password;
string redirect_url = Common.Extensions.StringExtensions.FromBase64(req["continue_with"].ToString() ?? string.Empty);
string token = req["g-recaptcha-response"];
Recaptcha data = null;
try
{
data = await RecaptchaResponse(Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RECAPTCHA_SECRET), token);
}
catch (Exception e)
{
Console.WriteLine("RECAPTCHA EXCEPTION");
Console.WriteLine(e.Message);
if (e.Message == "Resource temporarily unavailable Resource temporarily unavailable")
{
data = new Recaptcha() { Success = true };
Console.WriteLine("RECAPTCHA EXCEPTION - BYPASSED");
}
else
{
authresp.AuthStatus = false;
authresp.ErrorMessage = "Recaptcha error, try again";
}
}
Console.WriteLine("ENVIRONMENT-------->" + ViewBag.Env);
if (data != null && !data.Success && ViewBag.Env == "Production")//captcha error
{
Console.WriteLine("captcha error " + req["uname"]);
authresp.AuthStatus = false;
if (data.ErrorCodes.Count <= 0)
{
authresp.ErrorMessage = "The captcha input is invalid or malformed.";
}
string error = data.ErrorCodes[0].ToLower();
switch (error)
{
case ("missing-input-secret"):
authresp.CaptchaError = "The secret parameter is missing.";
break;
case ("invalid-input-secret"):
authresp.CaptchaError = "The secret parameter is invalid or malformed.";
break;
case ("missing-input-response"):
authresp.CaptchaError = "The captcha input is missing.";
break;
case ("invalid-input-response"):
authresp.CaptchaError = "The captcha input is invalid or malformed.";
break;
default:
authresp.CaptchaError = "Error occured. Please try again";
break;
}
}
else
{
if (req["otptype"] == "signinotp")
{
EbAuthResponse validateResp = ValidateOtp(req["otp"]);
UserName = req["uname_otp"];
Password = "NIL";
if (!validateResp.AuthStatus)
{
authresp.AuthStatus = false;
authresp.ErrorMessage = validateResp.ErrorMessage;
return authresp;
}
}
else if (req["otptype"] == "signupverify")
{
EbAuthResponse validateResp = ValidateSignUpVerify(req["otp"]);
UserName = req["uname_otp"];
Password = "NIL";
if (!validateResp.AuthStatus)
{
authresp.AuthStatus = false;
authresp.ErrorMessage = validateResp.ErrorMessage;
return authresp;
}
}
else
{
UserName = req["uname"];
Password = (req["pass"] + req["uname"]).ToMD5Hash();
// Password = (req["pass"].ToString().ToMD5Hash() + "3" + tenantid).ToMD5Hash();
}
Console.WriteLine("captcha ok " + req["uname"]);
try
{
Console.WriteLine("SolutionId: " + IntSolutionId + "\nConsole: " + WhichConsole);
Authenticate AuthenticateReq = new Authenticate
{
provider = CredentialsAuthProvider.Name,
UserName = UserName,
Password = Password,
Meta = new Dictionary<string, string> {
{ RoutingConstants.WC, WhichConsole },
{ TokenConstants.CID, IntSolutionId },
{ TokenConstants.IP, this.RequestSourceIp},
{ RoutingConstants.USER_AGENT, this.UserAgent}
},
RememberMe = true,
//UseTokenCookie = true
};
if (req["otptype"] == "signinotp" || req["otptype"] == "signupverify")
AuthenticateReq.Meta.Add("sso", "true");
myAuthResponse = this.AuthClient.Get<MyAuthenticateResponse>(AuthenticateReq);
if (req["otptype"] == "signinotp")
{
if (Convert.ToBoolean(req["forgotpassword"]))
{
this.ServiceClient.BearerToken = myAuthResponse.BearerToken;
this.ServiceClient.RefreshToken = myAuthResponse.RefreshToken;
this.ServiceClient.Post(new SetForgotPWInRedisRequest
{
UName = req["uname_otp"],
SolutionId = IntSolutionId,
});
}
}
}
catch (WebServiceException wse)
{
Console.WriteLine("Exception:" + wse.ToString());
authresp.AuthStatus = false;
authresp.ErrorMessage = wse.Message;
}
catch (Exception wse)
{
Console.WriteLine("Exception:" + wse.ToString());
authresp.AuthStatus = false;
authresp.ErrorMessage = wse.Message;
}
if (myAuthResponse != null) // authenticated
{
Console.WriteLine("myAuthResponse != null " + req["uname"]);
bool is2fa = false;
if (ViewBag.WhichConsole == "uc" && req["otptype"] != "signinotp")
{
Eb_Solution sol_Obj = GetSolutionObject(ViewBag.SolutionId);
if (sol_Obj != null && sol_Obj.Is2faEnabled)
is2fa = true;
}
if (is2fa) //if 2fa enabled
{
this.ServiceClient.BearerToken = myAuthResponse.BearerToken;
this.ServiceClient.RefreshToken = myAuthResponse.RefreshToken;
Authenticate2FAResponse resp = this.ServiceClient.Post(new Authenticate2FARequest
{
MyAuthenticateResponse = myAuthResponse,
SolnId = ViewBag.SolutionId,
});
authresp.AuthStatus = resp.AuthStatus;
authresp.ErrorMessage = resp.ErrorMessage;
authresp.Is2fa = resp.Is2fa;
authresp.OtpTo = resp.OtpTo;
CookieOptions options = new CookieOptions();
Response.Cookies.Append(RoutingConstants.TWOFATOKEN, resp.TwoFAToken, options);
Response.Cookies.Append(TokenConstants.USERAUTHID, myAuthResponse.User.AuthId, options);
Response.Cookies.Append("UserDisplayName", myAuthResponse.User.FullName, options);
if (req.ContainsKey("remember"))
Response.Cookies.Append("UserName", req["uname"], options);
}
else if (myAuthResponse.User.IsForcePWReset) //Force Password Reset
{
authresp.AuthStatus = true;
myAuthResponse.User.BearerToken = myAuthResponse.BearerToken;
myAuthResponse.User.RefreshToken = myAuthResponse.RefreshToken;
RouteToResetPage(myAuthResponse.User, Response);
authresp.RedirectUrl = RoutingConstants.RESET_PASSWORD_PAGE;
}
else//2fa NOT enabled
{
Console.WriteLine("AuthStatus true, not 2fa " + req["uname"]);
authresp.AuthStatus = true;
CookieOptions options = new CookieOptions();
Response.Cookies.Append(RoutingConstants.BEARER_TOKEN, myAuthResponse.BearerToken, options);
Response.Cookies.Append(RoutingConstants.REFRESH_TOKEN, myAuthResponse.RefreshToken, options);
Response.Cookies.Append(TokenConstants.USERAUTHID, myAuthResponse.User.AuthId, options);
Response.Cookies.Append("UserDisplayName", myAuthResponse.User.FullName, options);
Console.WriteLine("AuthStatus true, not 2fa cookie set" + req["uname"]);
if (req.ContainsKey("remember"))
Response.Cookies.Append("UserName", req["uname"], options);
string rdrct_url = this.HttpContext.Request.Cookies[RoutingConstants.REDIRECT_URL];
if (!string.IsNullOrEmpty(redirect_url))
authresp.RedirectUrl = redirect_url;
else if (string.IsNullOrEmpty(authresp.RedirectUrl) && !string.IsNullOrEmpty(rdrct_url))
{
Response.Cookies.Append(RoutingConstants.REDIRECT_URL, string.Empty, options);
authresp.RedirectUrl = rdrct_url;
}
else
authresp.RedirectUrl = this.RouteToDashboard(WhichConsole);
}
}
else
{
Console.WriteLine("captcha error " + req["uname"]);
}
}