public async Task Invoke(HttpContext httpContext, UserManager<ApplicationUser> manager)
        {
            if (httpContext.Request.Path.StartsWithSegments(_options.Path))
            {
                var headers = httpContext.Request.Headers;
                if (!(headers.ContainsKey("ApiUser") && headers.ContainsKey("ApiToken")))
                {
                    await httpContext.Authentication.ChallengeAsync();
                    return;
                }

                var apiUser = headers.FirstOrDefault(h => h.Key == "ApiUser").Value;
                var token = headers.FirstOrDefault(h => h.Key == "ApiToken").Value;

                var user = await manager.FindByNameAsync(apiUser).ConfigureAwait(false);
                var authorized = await manager.VerifyUserTokenAsync(user, "Default", "api-request-injest", token).ConfigureAwait(false);

                if (!authorized)
                {
                    await httpContext.Authentication.ChallengeAsync();
                    return;
                }
            }

            await _next(httpContext);
        }
        public string submitCodePost(string title, string content, string type)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                CodePost tmp = new CodePost();

                content = HttpUtility.JavaScriptStringEncode(content);

                var store = new UserStore<ApplicationUser>(db);
                var userManager = new UserManager<ApplicationUser>(store);
                ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;
                var currentUser = userManager.FindById(User.Identity.GetUserId());

                if (title != null && content != null && type != null)
                {
                    tmp.title = title;
                    tmp.content = content;
                    tmp.votes = 0;
                    tmp.user_id = user.Id;
                    tmp.userName = user.user;
                    tmp.userImgPath = currentUser.userImgPath;
                }

                bool result = updateHashTags(tmp);

                if(result == false)
                    db.posts.Add(tmp);

                db.SaveChanges();

                return "success";
            }
        }
        public ApplicationUser getAppUser(IPrincipal User)
        {
            var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
            var userManager = new UserManager<ApplicationUser>(store);
            ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;

            return user;
        }
Example #4
0
        private string GetUserId(string userName)
        {
            var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
            var userManager = new UserManager<ApplicationUser>(store);
            ApplicationUser user = userManager.FindByNameAsync(userName).Result;

            return user.Id;
        }
        public async Task<MyUser> GetUserByName(string name)
        {
            var db = new DataContext();
            var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
            
            var currentUser = await userMan.FindByNameAsync(name);

            return currentUser;
        }
 public static async Task SetDisplayName(this Controller baseController, ClaimsPrincipal user, UserManager<User> userManager)
 {
     if (baseController.TempData["UserDisplayName"] == null || string.IsNullOrEmpty(baseController.TempData["UserDisplayName"].ToString()))
     {
         if (user.Identity.IsAuthenticated)
         {
             var loggedInUser = await userManager.FindByNameAsync(user.Identity.Name);
             baseController.TempData["UserDisplayName"] = loggedInUser.GetFirstName();
         }
     }
 }
Example #7
0
 public ActionResult Index()
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;
     model = new ImageModel();
     if (user != null)
     {
         model.ImageUrl = user.ImageUrl;
     }
     return PartialView("~/Views/Shared/_LoginPartial.cshtml", model);
 }
 public ActionResult AddToCart(Product product)
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;
     List<Product> products = new List<Product>();
     user.UserCart.Products.Add(product);
     foreach (var item in user.UserCart.Products)
     {
         products.Add(item);
     }
     return View(products);
 }
 // GET: api/CalcReleases
 public IQueryable<CalcRelease> GetCalcRelease()
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
     ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;
     string[] myInClause = null;
     if (user.Scheme != null)
     {
         myInClause = user.Scheme.Split(',');
         return db.CalcRelease.Where(s => myInClause.Contains(s.Scheme));
     }
     else
     {
         return null;
     }
 }
Example #10
0
        // GET: Files/Create
        public ActionResult Create()
        {
            var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
            var userManager = new UserManager<ApplicationUser>(store);
            ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;

            if (user == null)
                return View();

            ViewBag.OwnerId = new SelectList(db.Users.Where(u => u.Id == user.Id), "Id", "FirstName");
            ViewBag.ReceiverId = AddFirstItem(new SelectList(db.Users, "Id", "FirstName"));
            ViewBag.GroupId = AddFirstItem(new SelectList(db.Groups, "GroupID", "GroupName"));

            return View();
        }
 public IQueryable<string> Get()
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
     ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;
     string[] myInClause = null;
     var response = Request.CreateResponse();
     if (user.Scheme != null)
     {
         myInClause = user.Scheme.Split(',');
         return db.Schemes.Where(s => myInClause.Contains(s.Name)).Select(m => m.Name).Distinct();
     }
     else
     {
         return null;
     }
 }
Example #12
0
        public async Task Invoke(HttpContext context, SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager)
        {
            if (context.User.Identity.IsAuthenticated)
            {
                this.SetNTContext(context);
            }

            // automatically logging in in the dev mode
            else if (SiteSettings.IsEnvironment(SecurityConstants.DevEnvironment))
            {
                ApplicationUser user = await userManager.FindByNameAsync(SecuritySettings.NootusProfileUserName);
                await signInManager.SignInAsync(user, false);
            }

            await this.next(context);
        }
		/// <summary>
		/// Invoked after the LTI request has been authenticated so the application can sign in the application user.
		/// </summary>
		/// <param name="context">Contains information about the login session as well as the LTI request.</param>
		/// <param name="claims">Optional set of claims to add to the identity.</param>
		/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
		public static async Task OnAuthenticated(LtiAuthenticatedContext context, IEnumerable<Claim> claims = null)
		{
			// Find existing pairing between LTI user and application user
			var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new LtiDb()));
			var loginProvider = string.Join(":", new[] { context.Options.AuthenticationType, context.LtiRequest.ConsumerKey });
			var providerKey = context.LtiRequest.UserId;
			var login = new UserLoginInfo(loginProvider, providerKey);
			var user = await userManager.FindAsync(login);
			if (user == null)
			{
				var usernameContext = new LtiGenerateUserNameContext(context.OwinContext, context.LtiRequest);
				await context.Options.Provider.GenerateUserName(usernameContext);
				if (string.IsNullOrEmpty(usernameContext.UserName))
				{
					return;
				}
				user = await userManager.FindByNameAsync(usernameContext.UserName);
				if (user == null)
				{
					user = new ApplicationUser { UserName = usernameContext.UserName };
					var result = await userManager.CreateAsync(user);
					if (!result.Succeeded)
					{
						return;
					}
				}
				// Save the pairing between LTI user and application user
				await userManager.AddLoginAsync(user.Id, login);
			}

			// Create the application identity, add the LTI request as a claim, and sign in
			var identity = await userManager.CreateIdentityAsync(user, context.Options.SignInAsAuthenticationType);
			identity.AddClaim(new Claim(context.Options.ClaimType, JsonConvert.SerializeObject(context.LtiRequest, Formatting.None,
					new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), ClaimValueTypes.String, context.Options.AuthenticationType));
			if (claims != null)
			{
				foreach (var claim in claims)
				{
					identity.AddClaim(claim);
				}
			}
			context.OwinContext.Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);

			// Redirect to original URL so the new identity takes affect
			context.RedirectUrl = context.LtiRequest.Url.ToString();
		}
        public async Task<WikiDownUser> Save(IPrincipal principal, UserManager<WikiDownUser> userManager)
        {
            var user = await userManager.FindByNameAsync(this.UserName);

            var roles = this.GetRoles(principal, user);

            if (user != null)
            {
                if (user.UserName == principal.Identity.Name)
                {
                    var userAccessLevel = ArticleAccessHelper.GetAccessLevel(user.Roles);
                    if (userAccessLevel < ArticleAccessLevel.Admin)
                    {
                        throw new HttpResponseException(HttpStatusCode.BadRequest);
                    }
                }

                user.SetRoles(roles);
                user.SetDisplayName(this.DisplayName);
                user.SetEmail(this.Email);

                if (!string.IsNullOrWhiteSpace(this.Password))
                {
                    await userManager.RemovePasswordAsync(user.Id);
                    await userManager.AddPasswordAsync(user.Id, this.Password);
                }

                await userManager.UpdateAsync(user);

                WikiDownUserCacheHelper.Clear(user.UserName);
            }
            else
            {
                user = new WikiDownUser(this.UserName) { Roles = roles };
                user.SetDisplayName(this.DisplayName);
                user.SetEmail(this.Email);

                await userManager.CreateAsync(user, this.Password);
            }

            return user;
        }
Example #15
0
        public async Task<IHttpActionResult> UpdateRuoloUtente(UpdateRuoloUtenteModel Model)
        {
            if (Model == null || !ModelState.IsValid)
                return BadRequest(ModelState);

            using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
            {
                var utente = await userManager.FindByNameAsync(Model.Username);
                if (utente == null)
                    return NotFound();

                if (Model.NuovoStato)
                {
                    await userManager.AddToRoleAsync(utente.Id, Model.Ruolo);
                }
                else
                {
                    await userManager.RemoveFromRoleAsync(utente.Id, Model.Ruolo);
                }
            }

            return Ok();
        }
Example #16
0
 public async Task<Post> SetUser(UserManager<User> userManager)
 {
     var user = await userManager.FindByNameAsync(UserName);
     User = user == null ? new User { UserName = "Default" } : user;
     return this;
 }
 public ActionResult SchemeAddToUser(string UserName, string[] SchemeName)
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
     ApplicationUser user = userManager.FindByNameAsync(UserName).Result;
     user.Scheme = string.Join(",", SchemeName);
     userManager.Update(user);
     ViewBag.ResultMessageAddScheme = "Scheme's added to User successfully";
     // prepopulat roles for the view dropdown
     var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
     var schemeList = db.Schemes.Select(m => new { Value = m.Name, Text = m.Name }).Distinct().ToList();
     ViewBag.Roles = list;
     var listUsers = context.Users.OrderBy(r => r.UserName).ToList().Select(rr => new SelectListItem { Value = rr.UserName.ToString(), Text = rr.UserName }).ToList();
     ViewBag.Users = listUsers;
     ViewBag.SchemeList = new MultiSelectList(schemeList, "Value", "Text");
     return View("Index");
 }
Example #18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, UserManager<ApplicationUser> userManager, ApplicationDbContext ctx)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
            // Refactor this into a seperate class
            // Remove hard coding of the password in the installDevices routine!
            app.UseBasicAuthentication(o =>
            {
                o.Realm = $"j64 Alarm";

                o.Events = new BasicAuthenticationEvents
                {
                    OnSignIn = c =>
                    {
                        var x = userManager.FindByNameAsync(c.UserName);
                        x.Wait();
                        if (x.Result != null)
                        {
                            var y = userManager.CheckPasswordAsync(x.Result, c.Password);
                            y.Wait();

                            if (y.Result == true)
                            {
                                var z = userManager.GetClaimsAsync(x.Result);
                                z.Wait();
                                var identity = new ClaimsIdentity(z.Result, c.Options.AuthenticationScheme);
                                c.Principal = new ClaimsPrincipal(identity);
                            }
                        }

                        return Task.FromResult(true);
                    }
                };
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            // Seed some default entries into the database
            var task = new Data.UserDataInitializer(ctx, userManager).CreateMasterUser();
        }
        // GET: Project/ProjectConfigs
        public ActionResult Index()
        {
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            if (Request.IsAuthenticated)
            {

                ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;

                if (!userManager.IsInRole(User.Identity.GetUserId(),"Configuration") && !userManager.IsInRole(User.Identity.GetUserId(), "System Admin"))
                {
                    return RedirectToAction("AccessBlock", "Account", new { area = "" });
                }
                else
                {
                    return View();
                }
            }
            else
            {
                return RedirectToAction("Login", "Account", new { area = "" });
            }
        }
Example #20
0
        public static void Initialize()
        {
            eQuizContext db = new eQuizContext();

            using (var Transaction = db.Database.BeginTransaction())
            {
                try
                {
                    if (db.Questions.Count() == 0)
                    {
                        // question 1
                        var q1 = new Question();
                        q1.Text = "Which Helper Method Returns binary output to write to the response?";
                        db.Questions.Add(q1);
                        db.SaveChanges();

                        var a1 = new Answer();
                        a1.Text = "Content";
                        a1.IsCorrect = true;
                        a1.QuestionId = q1.QuestionId;
                        db.Answers.Add(a1);

                        var a2 = new Answer();
                        a2.Text = "File";
                        a2.IsCorrect = false;
                        a2.QuestionId = q1.QuestionId;
                        db.Answers.Add(a2);

                        var a3 = new Answer();
                        a3.Text = "JavaScript";
                        a3.IsCorrect = false;
                        a3.QuestionId = q1.QuestionId;
                        db.Answers.Add(a3);

                        var a4 = new Answer();
                        a4.Text = "Json";
                        a4.IsCorrect = false;
                        a4.QuestionId = q1.QuestionId;
                        db.Answers.Add(a4);

                        db.SaveChanges();

                        // question 2
                        var q2 = new Question();
                        q2.Text = "Which Action Result Renders a partial view, which defines a section of a view that can be rendered inside another view?";
                        db.Questions.Add(q2);
                        db.SaveChanges();

                        var q2a1 = new Answer();
                        q2a1.Text = "ContentResult";
                        q2a1.IsCorrect = false;
                        q2a1.QuestionId = q2.QuestionId;
                        db.Answers.Add(q2a1);

                        var q2a2 = new Answer();
                        q2a2.Text = "RedirectResult";
                        q2a2.IsCorrect = true;
                        q2a2.QuestionId = q2.QuestionId;
                        db.Answers.Add(q2a2);

                        var q2a3 = new Answer();
                        q2a3.Text = "PartialViewResult";
                        q2a3.IsCorrect = false;
                        q2a3.QuestionId = q2.QuestionId;
                        db.Answers.Add(q2a3);

                        var q2a4 = new Answer();
                        q2a4.Text = "None of above.";
                        q2a4.IsCorrect = false;
                        q2a4.QuestionId = q2.QuestionId;
                        db.Answers.Add(q2a4);

                        db.SaveChanges();

                        // question 3
                        var q3 = new Question();
                        q3.Text = "The Controller class is responsible for the following processing stages:";
                        db.Questions.Add(q3);
                        db.SaveChanges();

                        var q3a1 = new Answer();
                        q3a1.Text = "Locating the appropriate action method to call and validating that it can be called";
                        q3a1.IsCorrect = false;
                        q3a1.QuestionId = q3.QuestionId;
                        db.Answers.Add(q3a1);

                        var q3a2 = new Answer();
                        q3a2.Text = "Getting the values to use as the action method's arguments";
                        q3a2.IsCorrect = false;
                        q3a2.QuestionId = q3.QuestionId;
                        db.Answers.Add(q3a2);

                        var q3a3 = new Answer();
                        q3a3.Text = "Handling all errors that might occur during the execution of the action method";
                        q3a3.IsCorrect = false;
                        q3a3.QuestionId = q3.QuestionId;
                        db.Answers.Add(q3a3);

                        var q3a4 = new Answer();
                        q3a4.Text = "All of the above.";
                        q3a4.IsCorrect = true;
                        q3a4.QuestionId = q3.QuestionId;
                        db.Answers.Add(q3a4);

                        db.SaveChanges();
                    }

                    //this is for creating user
                    var userStore = new UserStore<ApplicationUser>(db);
                    var userManager = new UserManager<ApplicationUser>(userStore);

                    if (!(db.Users.Any(u => u.UserName == "[email protected]")))
                    {
                        var userToInsert = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]", PhoneNumber = "03035332033", LockoutEnabled = true, FirstName = "Muhammad", LastName = "Sohail" };
                        userManager.Create(userToInsert, "[email protected]");
                    }

                    if (!(db.Users.Any(u => u.UserName == "[email protected]")))
                    {
                        var userToInsert = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]", PhoneNumber = "03035332033", LockoutEnabled = true, FirstName = "Melvin", LastName = "Claxton" };
                        userManager.Create(userToInsert, "123456");
                    }

                    //this is for creating/getting role
                    RoleManager<IdentityRole> RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
                    var role = new IdentityRole("Administrator");
                    if (!RoleManager.RoleExists("Administrator"))
                    {
                        RoleManager.Create(role);
                    }
                    else
                    {
                        role = RoleManager.FindByName("Administrator");
                    }

                    //this is for assigning role that is created above
                    ApplicationUser user = userManager.FindByNameAsync("[email protected]").Result;
                    if(!userManager.IsInRole(user.Id, role.Id))
                    {
                        userManager.AddToRole(user.Id, role.Name);
                    }

                    //this is for assigning role that is created above
                    user = userManager.FindByNameAsync("[email protected]").Result;
                    if (!userManager.IsInRole(user.Id, role.Id))
                    {
                        userManager.AddToRole(user.Id, role.Name);
                    }

                    Transaction.Commit();
                }
                catch(Exception exc)
                {
                    Transaction.Rollback();
                }
            }

            using (var Transaction = db.Database.BeginTransaction())
            {
                try
                {
                    var Settings = db.Settings.ToList();
                    bool QuizStartTimeSettingExists = false;

                    foreach (var Setting in Settings)
                    {
                        if (Setting.Name.Contains("Quiz Start Time"))
                        {
                            QuizStartTimeSettingExists = true;
                            break;
                        }
                    }

                    if (!QuizStartTimeSettingExists)
                    {
                        db.Settings.Add(new Setting { Name = "Quiz Start Time", Value = "2020/01/01" });
                        db.SaveChanges();
                    }

                    Transaction.Commit();
                }
                catch (Exception exc)
                {
                    Transaction.Rollback();
                }
            }
        }
Example #21
0
 public string GetGender()
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;
     if (user.Gender == "M")
     { return "Male"; }
     else if (user.Gender == "F")
     { return "Female"; }
     else
     { return ""; }
 }
 /// <summary>
 /// Gets the user.
 /// </summary>
 /// <param name="WindowsPrincipal">The windows principal.</param>
 /// <returns>The user</returns>
 private static User GetUser(WindowsPrincipal WindowsPrincipal)
 {
     Contract.Requires<ArgumentNullException>(WindowsPrincipal != null, "WindowsPrincipal");
     Claim NameClaim = WindowsPrincipal.FindFirst(ClaimTypes.Name);
     string Name = NameClaim.Value;
     string[] Parts = Name.Split(new[] { '\\' }, 2);
     string ShortName = Parts[Parts.Length - 1];
     using (UserStore UserStore = new UserStore())
     {
         using (UserManager<User, long> UserManager = new UserManager<User, long>(UserStore))
         {
             User User = UserManager.FindByNameAsync(ShortName).Result;
             if (User == null)
             {
                 UserManager.CreateAsync(new User() { UserName = ShortName }, Guid.NewGuid().ToString()).Wait();
                 User = UserManager.FindByNameAsync(ShortName).Result;
             }
             return User;
         }
     }
 }
 public async Task<ApplicationUser> ReturnCurrentUserAsync()
 {
     var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
     var userManager = new UserManager<ApplicationUser>(store);
     ApplicationUser user = await userManager.FindByNameAsync(User.Identity.Name);
     store.Dispose();
     userManager.Dispose();
     return user;
 }
Example #24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleDataInitializer sampleData, UserManager<ApplicationUser> userManager)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
                try
                {
                    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                        .CreateScope())
                    {
                        serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
                             .Database.Migrate();
                    }
                }
                catch { }
            }

            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

            app.UseStaticFiles();

            app.UseIdentity();

            // Refactor this into a seperate class
            // Remove hard coding of the password in the installDevices routine!
            app.UseBasicAuthentication(o =>
            {
                o.Realm = $"j64 Alarm";

                o.Events = new BasicAuthenticationEvents
                {
                    OnSignIn = c =>
                    {
                        var x = userManager.FindByNameAsync(c.UserName);
                        x.Wait();
                        if (x.Result != null)
                        {
                            var y = userManager.CheckPasswordAsync(x.Result, c.Password);
                            y.Wait();

                            if (y.Result == true)
                            {
                                var z = userManager.GetClaimsAsync(x.Result);
                                z.Wait();
                                var identity = new ClaimsIdentity(z.Result, c.Options.AuthenticationScheme);
                                c.Principal = new ClaimsPrincipal(identity);
                            }
                        }

                        return Task.FromResult(true);
                    }
                };
            });
            
            // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            
            // Seed some default entries into the database
            var task = sampleData.CreateMasterUser();
        }
        public async Task<ActionResult> RegisterFinish(OrderViewModel modelObj, string slug)
        {
            if (modelObj == null) modelObj = new OrderViewModel();

            TryUpdateModel(modelObj);

            using (var ctx = new SportDataContext())
            {
                var userManager = new UserManager<User>(new UserStore<User>(ctx));
                var currentUser = await userManager.FindByIdAsync(User.Identity.GetUserId());

                var team = SearchService.FindTeam(modelObj.Entrant, ctx);
                if (team == null)                
                    team = modelObj.CreateTeam();

                var driver1 = await SearchService.FindUser(modelObj.Driver1License, ctx) ?? await SearchService.FindUserById(modelObj.Driver1Id, ctx) ?? await SearchService.FindUserName(modelObj.Driver1FirstName, modelObj.Driver1LastName, ctx);
                var driver2 = await SearchService.FindUser(modelObj.Driver2License, ctx) ?? await SearchService.FindUserById(modelObj.Driver2Id, ctx) ?? await SearchService.FindUserName(modelObj.Driver2FirstName, modelObj.Driver2LastName, ctx);

                //Защита от
                if (driver1==null || string.IsNullOrWhiteSpace(driver1.LastName + driver1.FirstName + "")) {
                    driver1 = modelObj.CreateDriver1();
                    var existingUser = await userManager.FindByNameAsync(driver1.UserName);
                    if (existingUser != null)
                        driver1.UserName = Guid.NewGuid().ToString();
                }
                if (driver2 == null || string.IsNullOrWhiteSpace(driver2.LastName + driver2.FirstName + ""))
                {
                    driver2 = modelObj.CreateDriver2();
                    var existingUser = await userManager.FindByNameAsync(driver2.UserName);
                    if (existingUser != null)
                        driver2.UserName = Guid.NewGuid().ToString();
                }

                var car = modelObj.CreateCar();

                var ev = await EventService.GetEvent(slug, ctx);

                Dictionary<SubEvent, Order> orders = new Dictionary<SubEvent,Order>();
                ViewBag.Error = null;
                if (driver1.Id == driver2.Id)
                {
                    ViewBag.Error = "В вашей заявке совпадают первый и второй водитель. Пожалуйста, проверьте правильность заполнения заявки. Если у вас в настоящее время нет полной информации о составе экипажа - оставьте недостающие поля пустыми.";                    
                }
                if (string.IsNullOrWhiteSpace(driver1.LastName + driver1.FirstName + driver2.LastName + driver2.FirstName))
                {
                    ViewBag.Error = "Укажите пожалуйста в заявке не менее 1 водителя.";                    
                }
                if (modelObj.Groups == null || modelObj.Groups.Count() == 0)
                {
                    ViewBag.Error = "В вашей заявке на " + ev.Title + " не указано ни одной зачетной группы. Пожалуйста, укажите минимум 1 зачет из списка.";                    
                }
                if(!string.IsNullOrWhiteSpace(ViewBag.Error))
                    return View("RegistrationError", ev);

                foreach (var group in modelObj.Groups)
                {
                    var tokens = group.Split('_');
                    var subEv = ev.SubEvents.First(e=>e.Id == int.Parse(tokens[0]));

                    if(!orders.ContainsKey(subEv)) {
                        orders.Add(subEv, new Order() {
                            Driver = driver1,
                            CoDriver = driver2,
                            Team = team,
                            Car = car,
                            Redimmed = false,
                            Confirmed = false,
                            CreatedAt= DateTime.Now,
                            StartNumber="",
                            Group = new List<Group>(),
                            CreatedBy = currentUser
                        });
                    }

                    orders[subEv].Group.Add(subEv.Groups.First(g => g.Id == int.Parse(tokens[1])));
                }

                foreach (var item in orders.Keys)
                {

                    item.Tag.Orders = item.Tag.Orders ?? new List<Order>();
                    item.Tag.Orders.Add(orders[item]);
                }
                try
                {
                    await ctx.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    throw;
                }

                return View("RegistrationComplete", ev);
            }
        }