-
Notifications
You must be signed in to change notification settings - Fork 1
/
CmsAdminController.cs
2944 lines (2233 loc) · 86.1 KB
/
CmsAdminController.cs
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 Carrotware.CMS.Core;
using Carrotware.CMS.CoreMVC.UI.Admin.Models;
using Carrotware.CMS.Interface;
using Carrotware.CMS.Interface.Controllers;
using Carrotware.CMS.Security;
using Carrotware.CMS.Security.Models;
using Carrotware.Web.UI.Components;
using Carrotware.Web.UI.Components.SessionData;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Net.Http.Headers;
using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Web;
/*
* CarrotCake CMS (MVC Core)
* http://www.carrotware.com/
*
* Copyright 2015, 2023, 2024 Samantha Copeland
* Dual licensed under the MIT or GPL Version 3 licenses.
*
* Date: June 2023, April 2024
*/
namespace Carrotware.CMS.CoreMVC.UI.Admin.Controllers {
[CmsAuthorize]
public class CmsAdminController : Controller {
public override void OnActionExecuting(ActionExecutingContext context) {
base.OnActionExecuting(context);
BaseWidgetController.WidgetStandaloneMode = false;
var path = context.HttpContext.Request.Path;
RouteValueDictionary vals = context.RouteData.Values;
string action = vals["action"].ToString().ToLowerInvariant();
string controller = vals["controller"].ToString().ToLowerInvariant();
context.RouteData.Values.Remove("area");
if (this.HttpContext.User.Identity.IsAuthenticated) {
//carveouts for setup
List<string> lstOKNoSiteActions = (new string[] { "login", "logoff", "about", "siteinfo", "siteindex", "filebrowser", "userindex", "roleindex", "userprofile", "changepassword" }).ToList();
//carvouts for anon pages
List<string> anonMethods = (new string[] { "login", "logoff", "about" }).ToList();
// use reflection to see if the method/action has an anon permission and honor it
anonMethods = (this).GetType().GetMethods()
.Where(m => m.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Length > 0)
.Select(x => x.Name.ToLowerInvariant())
.Where(x => x == action)
.Distinct().ToList();
try {
if (!anonMethods.Contains(action)) {
if (!lstOKNoSiteActions.Contains(action) && !SiteData.CurrentSiteExists) {
context.Result = new RedirectResult(SiteFilename.SiteInfoURL);
return;
}
}
} catch (Exception ex) {
//something bad has gone down, toss back the error
SiteData.WriteDebugException("onactionexecuting", ex);
throw;
}
}
}
protected ManageSecurity securityHelper = new ManageSecurity();
protected ContentPageHelper pageHelper = new ContentPageHelper();
protected SiteData siteHelper = new SiteData();
protected WidgetHelper widgetHelper = new WidgetHelper();
protected CMSConfigHelper cmsHelper = new CMSConfigHelper();
protected string CurrentDLLVersion {
get { return SiteData.CurrentDLLVersion; }
}
protected Guid CurrentSiteID {
get {
return SiteData.CurrentSiteID;
}
}
protected void NoCache() {
this.HttpContext.Response.GetTypedHeaders()
.CacheControl =
new CacheControlHeaderValue() {
Public = true,
NoCache = true,
MaxAge = TimeSpan.FromMinutes(-1)
};
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult LogOff() {
ClearUserSession();
SessionContext.CleanExpiredSession();
//after signout, take to login
if (!SecurityData.IsAuthenticated) {
return RedirectToAction(this.GetActionName(x => x.Login("")));
}
return RedirectToAction(this.GetActionName(x => x.Index()));
}
[HttpGet]
public ActionResult UserProfile() {
ExtendedUserData model = new ExtendedUserData(SecurityData.CurrentUserIdentityName);
ShowSaved("Profile Updated");
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> UserProfile(ExtendedUserData model) {
if (ModelState.IsValid) {
IdentityResult result = await securityHelper.UserManager.SetEmailAsync(SecurityData.CurrentIdentityUser, model.Email);
var exUsr = new ExtendedUserData(SecurityData.CurrentUserIdentityName);
exUsr.UserNickName = model.UserNickName;
exUsr.FirstName = model.FirstName;
exUsr.LastName = model.LastName;
exUsr.UserBio = model.UserBio;
exUsr.Save();
if (result.Succeeded) {
SetSaved();
return RedirectToAction(SiteActions.UserProfile);
}
}
Helper.HandleErrorDict(ModelState);
return View(model);
}
[HttpGet]
[CmsAdminAuthorize]
public ActionResult UserEdit(Guid id) {
UserModel model = new UserModel(id);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
[CmsAdminAuthorize]
public async Task<ActionResult> UserEdit(UserModel model) {
ExtendedUserData userExt = model.User;
if (ModelState.IsValid) {
var user = await securityHelper.UserManager.FindByNameAsync(model.User.UserName);
IdentityResult result = await securityHelper.UserManager.SetEmailAsync(user, userExt.Email);
result = await securityHelper.UserManager.SetPhoneNumberAsync(user, userExt.PhoneNumber);
if (userExt.LockoutEndDateUtc.HasValue) {
if (!user.LockoutEnd.HasValue) {
// set lockout
user.LockoutEnd = userExt.LockoutEndDateUtc.Value;
user.AccessFailedCount = 20;
await securityHelper.UserManager.UpdateAsync(user);
}
} else {
if (user.LockoutEnd.HasValue) {
// unset lockout
user.LockoutEnd = null;
user.AccessFailedCount = 0;
await securityHelper.UserManager.UpdateAsync(user);
}
}
ExtendedUserData exUsr = new ExtendedUserData(userExt.UserId);
exUsr.UserNickName = userExt.UserNickName;
exUsr.FirstName = userExt.FirstName;
exUsr.LastName = userExt.LastName;
exUsr.UserBio = userExt.UserBio;
exUsr.Save();
model.SaveOptions();
return RedirectToAction(SiteActions.UserEdit, new { @id = userExt.UserId });
}
Helper.HandleErrorDict(ModelState);
return View(model);
}
[HttpGet]
[CmsAdminAuthorize]
public ActionResult UserAdd() {
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[CmsAdminAuthorize]
public async Task<ActionResult> UserAdd(RegisterViewModel model) {
if (ModelState.IsValid) {
SecurityData sd = new SecurityData();
IdentityUser user = new IdentityUser { UserName = model.UserName, Email = model.Email };
var newUser = await sd.CreateIdentityUser(user, model.Password);
var result = newUser.IdentityResult;
var exUser = newUser.ExtendedUserData;
user = SecurityData.NewIdentityUser(exUser);
if (result == IdentityResult.Success && exUser != null) {
result = await securityHelper.UserManager.SetLockoutEnabledAsync(user, true);
return RedirectToAction(SiteActions.UserEdit, new { @id = exUser.UserId });
}
AddErrors(result);
}
Helper.HandleErrorDict(ModelState);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult AjaxFileUpload(AjaxFileUploadModel model) {
List<IFormFile> files = model.PostedFiles.ToList();
if (files != null && files.Any()) {
foreach (IFormFile file in files) {
string res = model.UploadFile(file);
return Json(res);
}
}
return Json(string.Empty);
}
[HttpGet]
public ActionResult FileBrowser(string fldrpath, string useTiny, string returnvalue, string viewmode) {
FileBrowserModel model = new FileBrowserModel(fldrpath, useTiny, returnvalue, viewmode);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult FileBrowser(FileBrowserModel model) {
string msg = string.Empty;
string msgCss = string.Empty;
if (ModelState.IsValid) {
model.UploadFile();
msg = model.FileMsg;
msgCss = model.FileMsgCss;
model = new FileBrowserModel(model.QueryPath, model.UseTinyMCE.ToString(), model.ReturnMode.ToString(), model.ViewMode);
model.FileMsg = msg;
model.FileMsgCss = msgCss;
ModelState.Clear();
}
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult FileBrowserRemove(FileBrowserModel model) {
model.RemoveFiles();
ModelState.Clear();
return RedirectToAction(SiteActions.FileBrowser, new { @fldrpath = model.QueryPath, @useTiny = model.UseTinyMCE, @returnvalue = model.ReturnMode, @viewmode = model.ViewMode });
}
[HttpGet]
public ActionResult SiteDataExport() {
return View();
}
[HttpGet]
public ActionResult SiteImport(Guid importid) {
SiteImportNativeModel model = new SiteImportNativeModel(importid);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SiteImport(SiteImportNativeModel model) {
ModelState.Clear();
model.ImportStuff();
string msg = model.Message;
bool loaded = true;
if (!model.HasLoaded) {
loaded = false;
ModelState.AddModelError(string.Empty, "No Items Selected For Import");
}
model = new SiteImportNativeModel(model.ImportID);
model.Message = msg;
model.HasLoaded = loaded;
Helper.HandleErrorDict(ModelState);
return View(model);
}
[HttpGet]
public ActionResult SiteImportWP(Guid importid) {
SiteImportWordpressModel model = new SiteImportWordpressModel(importid);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SiteImportWP(SiteImportWordpressModel model) {
ModelState.Clear();
bool loaded = true;
if (model.DownloadImages && string.IsNullOrEmpty(model.SelectedFolder)) {
ModelState.AddModelError(model.GetPropertyName(x => x.SelectedFolder), "If download images is selected, you must select a target folder.");
}
loaded = ModelState.IsValid;
if (ModelState.IsValid) {
model.ImportStuff();
if (!model.HasLoaded) {
loaded = false;
ModelState.AddModelError(string.Empty, "No Items Selected For Import");
}
}
var newmodel = new SiteImportWordpressModel(model.ImportID);
newmodel.Message = model.Message;
newmodel.HasLoaded = loaded;
newmodel.PageTemplate = model.PageTemplate;
newmodel.PostTemplate = model.PostTemplate;
newmodel.SelectedFolder = model.SelectedFolder;
newmodel.ImportPages = model.ImportPages;
newmodel.ImportPosts = model.ImportPosts;
newmodel.ImportSite = model.ImportSite;
newmodel.DownloadImages = model.DownloadImages;
newmodel.FixHtmlBodies = model.FixHtmlBodies;
newmodel.CreateUsers = model.CreateUsers;
newmodel.MapUsers = model.MapUsers;
Helper.HandleErrorDict(ModelState);
return View(newmodel);
}
[HttpGet]
public ActionResult ContentImport() {
CMSConfigHelper.CleanUpSerialData();
FileUpModel model = new FileUpModel();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ContentImport(FileUpModel model) {
string sXML = string.Empty;
//TODO: fix stream
if (model.PostedFile != null) {
using (var sr = new StreamReader(model.PostedFile.OpenReadStream())) {
sXML = sr.ReadToEnd();
}
}
string sTest = string.Empty;
if (!string.IsNullOrWhiteSpace(sXML) && sXML.Length >= 256) {
sTest = sXML.Substring(0, 256);
if (sXML.Length >= 512) {
sTest = sXML.Substring(0, 512);
}
if (sXML.Length >= 1024) {
sTest = sXML.Substring(0, 1024);
}
sTest = sTest.ToLowerInvariant().Replace("\r\n", " ").Replace("\r", "\n").Replace("\n", " ");
try {
if (sTest.Contains("<contentpageexport xmlns:xsi=\"http://www.w3.org/2001/xmlschema-instance\" xmlns:xsd=\"http://www.w3.org/2001/xmlschema\">")
|| sTest.Contains("<contentpageexport xmlns:xsd=\"http://www.w3.org/2001/xmlschema\" xmlns:xsi=\"http://www.w3.org/2001/xmlschema-instance\">")) {
ContentPageExport cph = ContentImportExportUtils.DeserializeContentPageExport(sXML);
ContentImportExportUtils.AssignContentPageExportNewIDs(cph);
ContentImportExportUtils.MapSiteCategoryTags(cph);
ContentImportExportUtils.SaveSerializedDataExport<ContentPageExport>(cph.NewRootContentID, cph);
if (cph.ThePage.ContentType == ContentPageType.PageType.ContentEntry) {
//Response.Redirect(SiteFilename.PageAddEditURL + "?importid=" + cph.NewRootContentID.ToString());
return RedirectToAction(this.GetActionName(x => x.PageAddEdit(null)), new { importid = cph.NewRootContentID });
} else {
//Response.Redirect(SiteFilename.BlogPostAddEditURL + "?importid=" + cph.NewRootContentID.ToString());
return RedirectToAction(this.GetActionName(x => x.BlogPostAddEdit(null)), new { importid = cph.NewRootContentID });
}
}
if (sTest.Contains("<siteexport xmlns:xsi=\"http://www.w3.org/2001/xmlschema-instance\" xmlns:xsd=\"http://www.w3.org/2001/xmlschema\">")
|| sTest.Contains("<siteexport xmlns:xsd=\"http://www.w3.org/2001/xmlschema\" xmlns:xsi=\"http://www.w3.org/2001/xmlschema-instance\">")) {
SiteExport site = ContentImportExportUtils.DeserializeSiteExport(sXML);
ContentImportExportUtils.AssignSiteExportNewIDs(site);
ContentImportExportUtils.SaveSerializedDataExport<SiteExport>(site.NewSiteID, site);
//Response.Redirect(SiteFilename.SiteImportURL + "?importid=" + site.NewSiteID.ToString());
return RedirectToAction(SiteActions.SiteImport, new { importid = site.NewSiteID });
}
if (sXML.Contains("<channel>") && sXML.Contains("<rss")) {
int iChnl = sXML.IndexOf("<channel>");
sTest = sXML.Substring(0, iChnl).ToLowerInvariant();
}
if (sTest.Contains("this is a wordpress extended rss file generated by wordpress as an export")
&& sTest.Contains("://purl.org/rss")
&& sTest.Contains("://wordpress.org/export")) {
WordPressSite wps = ContentImportExportUtils.DeserializeWPExport(sXML);
ContentImportExportUtils.AssignWPExportNewIDs(SiteData.CurrentSite, wps);
ContentImportExportUtils.SaveSerializedDataExport<WordPressSite>(wps.NewSiteID, wps);
return RedirectToAction(SiteActions.SiteImportWP, new { importid = wps.NewSiteID });
}
ModelState.AddModelError(model.GetPropertyName(x => x.PostedFile), "File did not appear to match an expected format.");
} catch (Exception ex) {
ModelState.AddModelError(model.GetPropertyName(x => x.PostedFile), ex.ToString());
}
} else {
ModelState.AddModelError(model.GetPropertyName(x => x.PostedFile), "No file appeared in the upload queue.");
}
Helper.HandleErrorDict(ModelState);
return View(model);
}
[HttpGet]
public ActionResult SiteIndex() {
PagedData<SiteData> model = new PagedData<SiteData>();
model.PageSize = -1;
model.InitOrderBy(x => x.SiteName);
var srt = model.ParseSort();
var query = SiteData.GetSiteList().SortByParm(srt.SortField, srt.SortDirection);
model.TotalRecords = -1;
model.DataSource = query.ToList();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SiteIndex(PagedData<SiteData> model) {
model.ToggleSort();
var srt = model.ParseSort();
var query = SiteData.GetSiteList().SortByParm(srt.SortField, srt.SortDirection);
model.TotalRecords = -1;
model.DataSource = query.ToList();
ModelState.Clear();
return View(model);
}
[HttpGet]
public ActionResult ContentSnippetIndex() {
PagedData<ContentSnippet> model = new PagedData<ContentSnippet>();
model.PageSize = -1;
model.InitOrderBy(x => x.ContentSnippetName);
var srt = model.ParseSort();
var query = SiteData.CurrentSite.GetContentSnippetList().SortByParm(srt.SortField, srt.SortDirection);
model.TotalRecords = -1;
model.DataSource = query.ToList();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ContentSnippetIndex(PagedData<ContentSnippet> model) {
model.ToggleSort();
var srt = model.ParseSort();
var query = SiteData.CurrentSite.GetContentSnippetList().SortByParm(srt.SortField, srt.SortDirection);
model.TotalRecords = -1;
model.DataSource = query.ToList();
ModelState.Clear();
return View(model);
}
[HttpGet]
public ActionResult ContentSnippetHistory(Guid id) {
ContentSnippetHistoryModel model = new ContentSnippetHistoryModel(id);
ShowSaved();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ContentSnippetHistory(ContentSnippetHistoryModel model) {
ModelState.Clear();
List<Guid> lstDel = model.History.DataSource.Where(x => x.Selected).Select(x => x.ContentSnippetID).ToList();
foreach (Guid delID in lstDel) {
ContentSnippet.GetVersion(delID).DeleteThisVersion();
}
if (lstDel.Any()) {
SetSaved();
}
return RedirectToAction(SiteActions.ContentSnippetHistory, new { @id = model.Item.Root_ContentSnippetID });
}
public ActionResult ChangePassword() {
ViewBag.ChangePasswordSuccess = "";
if (this.TempData["cmsChangePasswordSuccess"] != null) {
ViewBag.ChangePasswordSuccess = this.TempData["cmsChangePasswordSuccess"].ToString();
}
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model) {
ViewBag.ChangePasswordSuccess = "";
if (!ModelState.IsValid) {
return View(model);
}
var user = SecurityData.CurrentIdentityUser;
if (user != null) {
var result = await securityHelper.UserManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded) {
await securityHelper.SignInManager.SignInAsync(user, false);
this.TempData["cmsChangePasswordSuccess"] = "Password change success!";
return RedirectToAction(SiteActions.ChangePassword, new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
}
return View(model);
}
[AllowAnonymous]
public ActionResult DatabaseSetup(string signout) {
if (!string.IsNullOrEmpty(signout)) {
ClearUserSession();
Response.Redirect(SiteFilename.DatabaseSetupURL);
}
SessionContext.CleanExpiredSession();
var model = new DatabaseSetupModel();
return View(model);
}
[AllowAnonymous]
public ActionResult CreateFirstAdmin() {
RedirectIfUsersExist();
if (SecurityData.IsAuthenticated) {
ClearUserSession();
return RedirectToAction(SiteActions.CreateFirstAdmin, new { @signout = true });
}
RegisterViewModel model = new RegisterViewModel();
return View(model);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CreateFirstAdmin(RegisterViewModel model) {
RedirectIfUsersExist();
if (ModelState.IsValid) {
ClearUserSession();
SecurityData sd = new SecurityData();
IdentityUser user = new IdentityUser { UserName = model.UserName, Email = model.Email };
var create = await sd.CreateIdentityUser(user, model.Password);
var result = create.IdentityResult;
var exUser = create.ExtendedUserData;
if (result.Succeeded) {
SecurityData.AddUserToRole(model.UserName, SecurityData.CMSGroup_Admins);
SecurityData.AddUserToRole(model.UserName, SecurityData.CMSGroup_Users);
return RedirectToAction(this.GetActionName(x => x.Index()));
}
AddErrors(result);
}
Helper.HandleErrorDict(ModelState);
return View(model);
}
[AllowAnonymous]
public ActionResult Login(string? returnUrl) {
NoCache();
RedirectIfNoUsersExist();
SessionContext.CleanExpiredSession();
LoginViewModel model = new LoginViewModel();
model.ReturnUrl = HttpUtility.UrlEncode(returnUrl);
return View(model);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model) {
Helper.ForceValidation(ModelState, model);
if (!ModelState.IsValid) {
Helper.HandleErrorDict(ModelState);
return View(model);
}
string returnUrl = !string.IsNullOrEmpty(model.ReturnUrl) ? HttpUtility.UrlDecode(model.ReturnUrl) : SiteFilename.DashboardURL;
// This doesn't count login failures towards account lockout
var user = await securityHelper.UserManager.FindByNameAsync(model.UserName);
var result = await securityHelper.SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, true);
if (result.Succeeded) {
await securityHelper.UserManager.ResetAccessFailedCountAsync(user);
return RedirectToLocal(returnUrl);
} else {
if (result.IsLockedOut) {
return View("Lockout");
} else {
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
if (user != null && user.LockoutEnd.HasValue && user.LockoutEnd.Value < DateTime.UtcNow) {
user.LockoutEnd = null;
user.AccessFailedCount = 1;
await securityHelper.UserManager.UpdateAsync(user);
}
}
}
return View(model);
}
[AllowAnonymous]
public ActionResult ResetPassword(string? token) {
var model = new ResetPasswordViewModel();
model.Token = token ?? string.Empty;
return View(model);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model) {
if (!ModelState.IsValid) {
Helper.HandleErrorDict(ModelState);
return View(model);
}
var user = await securityHelper.UserManager.FindByEmailAsync(model.Email);
if (user == null) {
// Don't reveal that the user does not exist
return RedirectToAction(SiteActions.ResetPasswordConfirmation);
}
SecurityData sd = new SecurityData();
var result = await sd.ResetPassword(user, model.Token, model.Password);
if (result.Succeeded) {
return RedirectToAction(SiteActions.ResetPasswordConfirmation);
}
AddErrors(result);
Helper.HandleErrorDict(ModelState);
return View();
}
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation() {
return View();
}
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation() {
return View();
}
[AllowAnonymous]
public ActionResult NotAuthorized() {
return View();
}
[AllowAnonymous]
public ActionResult ForgotPassword() {
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model) {
if (ModelState.IsValid) {
var user = await securityHelper.UserManager.FindByEmailAsync(model.Email);
if (user == null) {
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
} else {
SecurityData sd = new SecurityData();
await sd.ResetPassword(model.Email);
return RedirectToAction(SiteActions.ForgotPasswordConfirmation);
}
}
Helper.HandleErrorDict(ModelState);
// If we got this far, something failed, redisplay form
return View(model);
}
public ActionResult Index() {
NoCache();
RedirectIfNoUsersExist();
DashboardInfo model = new DashboardInfo();
CMSConfigHelper.CleanUpSerialData();
SessionContext.CleanExpiredSession();
model.Pages = pageHelper.GetSitePageCount(this.CurrentSiteID, ContentPageType.PageType.ContentEntry);
model.Posts = pageHelper.GetSitePageCount(this.CurrentSiteID, ContentPageType.PageType.BlogEntry);
model.Categories = ContentCategory.GetSiteCount(this.CurrentSiteID);
model.Tags = ContentTag.GetSiteCount(this.CurrentSiteID);
model.Snippets = pageHelper.GetSiteSnippetCount(this.CurrentSiteID);
return View(model);
}
[AllowAnonymous]
public ActionResult About() {
NoCache();
return View();
}
protected void LoadTimeZoneInfo() {
var now = DateTime.Now;
if (SiteData.CurrentSite != null) {
// site is pre-existing
now = SiteData.CurrentSite.Now;
}
var lstTZ = TimeZoneInfo.GetSystemTimeZones();
ViewBag.TimeZoneInfoList = (from z in lstTZ
select new {
Id = z.Id,
DisplayNameCurrent2 = "(UTC" +
(z.GetUtcOffset(now).Hours != 0 ?
(z.GetUtcOffset(now).Hours >= 0 ? "+" : "-") + z.GetUtcOffset(now).ToString("hh\\:mm")
: string.Empty) + ") "
+ (z.IsDaylightSavingTime(now) ? z.DaylightName : z.StandardName),
DisplayNameCurrent = z.DisplayName,
DisplayName = z.DisplayName,
UtcOffset = z.GetUtcOffset(now),
StandardName = z.StandardName,
DaylightName = z.DaylightName
}).OrderBy(x => x.DisplayNameCurrent).OrderBy(x => x.UtcOffset).ToList();
}
protected void LoadDatePattern() {
Dictionary<string, string> lst = new Dictionary<string, string>();
lst.Add("yyyy/MM/dd", "YYYY/MM/DD");
lst.Add("yyyy/M/d", "YYYY/M/D");
lst.Add("yyyy/MM", "YYYY/MM");
lst.Add("yyyy/MMMM", "YYYY/MonthName");
lst.Add("yyyy", "YYYY");
ViewBag.DatePatternList = lst;
}
[HttpGet]
public ActionResult CategoryAddEdit(Guid? id) {
ContentCategory model = null;
if (id.HasValue) {
model = ContentCategory.Get(id.Value);
}
if (model == null) {
model = new ContentCategory();
model.ContentCategoryID = Guid.Empty;
}
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CategoryAddEdit(ContentCategory model) {
Helper.ForceValidation(ModelState, model);
model.ClearOptionalItems(ModelState);
if (ModelState.IsValid) {
ContentCategory item = ContentCategory.Get(model.ContentCategoryID);
if (item == null || (item != null && item.ContentCategoryID == Guid.Empty)) {
item = new ContentCategory();
item.SiteID = CurrentSiteID;
item.ContentCategoryID = Guid.NewGuid();
}
item.CategorySlug = model.CategorySlug;
item.CategoryText = model.CategoryText;
item.IsPublic = model.IsPublic;
item.Save();
return RedirectToAction(SiteActions.CategoryAddEdit, new { @id = item.ContentCategoryID });
}
Helper.HandleErrorDict(ModelState);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CategoryDelete(ContentCategory model) {
model.ClearOptionalItems(ModelState);
ContentCategory item = ContentCategory.Get(model.ContentCategoryID);
item.Delete();
return RedirectToAction(SiteActions.CategoryIndex);
}
[HttpGet]
public ActionResult TagAddEdit(Guid? id) {
ContentTag model = null;
if (id.HasValue) {
model = ContentTag.Get(id.Value);
}
if (model == null) {
model = new ContentTag();
model.ContentTagID = Guid.Empty;
}
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult TagAddEdit(ContentTag model) {
Helper.ForceValidation(ModelState, model);
model.ClearOptionalItems(ModelState);
if (ModelState.IsValid) {
ContentTag item = ContentTag.Get(model.ContentTagID);
if (item == null || (item != null && item.ContentTagID == Guid.Empty)) {
item = new ContentTag();
item.SiteID = CurrentSiteID;
item.ContentTagID = Guid.NewGuid();
}
item.TagSlug = model.TagSlug;
item.TagText = model.TagText;
item.IsPublic = model.IsPublic;
item.Save();
return RedirectToAction(SiteActions.TagAddEdit, new { @id = item.ContentTagID });
}
Helper.HandleErrorDict(ModelState);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult TagDelete(ContentTag model) {
model.ClearOptionalItems(ModelState);
ContentTag item = ContentTag.Get(model.ContentTagID);
item.Delete();
return RedirectToAction(SiteActions.TagIndex);
}
[HttpGet]
[CmsAdminAuthorize]
public ActionResult SiteDetail(Guid id) {
SiteModel model = new SiteModel(id);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
[CmsAdminAuthorize]
public ActionResult SiteDetail(SiteModel model) {
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
[CmsAdminAuthorize]
public ActionResult SiteAddUser(SiteModel model) {
ModelState.Clear();
if (string.IsNullOrEmpty(model.NewUserId)) {
ModelState.AddModelError(model.GetPropertyName(x => x.NewUserId), "The New User field is required.");
}
SiteData site = model.Site;
Helper.ForceValidation(ModelState, model);
if (ModelState.IsValid) {
if (!string.IsNullOrEmpty(model.NewUserId)) {
ExtendedUserData exUsr = new ExtendedUserData(new Guid(model.NewUserId));
exUsr.AddToSite(site.SiteID);
if (model.NewUserAsEditor) {
exUsr.AddToRole(SecurityData.CMSGroup_Editors);
}
}
return RedirectToAction(SiteActions.SiteDetail, new { @id = site.SiteID });
}
Helper.HandleErrorDict(ModelState);
model.LoadUsers();
return View("SiteDetail", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
[CmsAdminAuthorize]
public ActionResult SiteRemoveUsers(SiteModel model) {
ModelState.Clear();
SiteData site = model.Site;
if (ModelState.IsValid) {
List<UserModel> usrs = model.Users.Where(x => x.Selected).ToList();