Пример #1
0
        public bool CreateUserAccount(string userName, string email, string password)
        {
            try
            {
                var user = new User
                {
                    Email = email,
                    Name = userName,
                    Password = password
                };

                using (var db = new Entities())
                {
                    db.User.Add(user);
                    db.SaveChanges();
                }

                return true;
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                return false;
            }
        }
Пример #2
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    // Create a profile, password, and link the local login before signing in the user
                    User user = new User(model.UserName);
                    if (await Users.Create(user) &&
                        await Secrets.Create(new UserSecret(model.UserName, model.Password)) &&
                        await Logins.Add(new UserLogin(user.Id, IdentityConfig.LocalLoginProvider, model.UserName)))
                    {
                        await SignIn(user.Id, isPersistent: false);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError(String.Empty, "Failed to create login for: " + model.UserName);
                    }
                }
                catch (DbEntityValidationException e)
                {
                    ModelState.AddModelError("", e.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #3
0
        // GET: User
        public ActionResult Index(string id)
        {
            if (id == null)
            {
                if (User.Identity.IsAuthenticated)
                {
                    var userID = User.Identity.GetUserId();
                    ApplicationUser user = db.Users.Where(c => c.Id == userID).First();

                    return RedirectToAction("Index", new { id = user.UserSecureID });
                }
            }
            else
            {
                // Niezbyt ta obsługa wyjątków działa, miejmy nadzieję, że nikt nie będzie
                // grzebał przy adresach, bo się posypie.
                try
                {
                    var model = new User(id);
                    return View(model);
                }
                catch(NullReferenceException)
                {
                    return RedirectToAction(
                        "NotFound", 
                        "Home", 
                        new {
                            message = "Nie odnaleziono użytkownika o podanej nazwie"
                        });
                }
            }
            return RedirectToAction("Index", "Home");
        }
Пример #4
0
 public FriendsPartialViewModel(
     User UserData
     )
 {
     CurrentUser.SecureID = UserData.UserSecureID;
     CurrentUser.Name     = UserData.UserName;
     CurrentUser.Status   = UserData.Status;
     this.Friends         = UserData.Friends;
 }
Пример #5
0
 public ActionResult RemoveFriend([Bind(Include = "UserSecureID")]FriendBtnViewModel model)
 {
     if (ModelState.IsValid &&
         User.Identity.IsAuthenticated)
     {
         ApplicationUser friend = db.Users.Where(c => c.UserSecureID == model.UserSecureID).First();
         User user = new User(db.Users.Find(User.Identity.GetUserId()));
         user.RemoveFriend(friend.Id);
     }
     return RedirectToAction("FriendBtn", (object)model.UserSecureID);
 }
Пример #6
0
        public async Task <IActionResult> PutUser(
            [FromRoute] string id,
            [FromHeader] string jwttoken,
            [FromBody] User user)
        {
            // Permission Level User
            if (this.jwtService.PermissionLevelValid(jwttoken, "user"))
            {
                try
                {
                    if (this.jwtService.GetUIDfromJwtKey(jwttoken) == id)
                    {
                        if (!this.ModelState.IsValid)
                        {
                            return(this.BadRequest(this.ModelState));
                        }

                        if (id != user.UID)
                        {
                            return(this.BadRequest());
                        }

                        this._context.Entry(user).State = EntityState.Modified;
                        this._context.Entry(user).Property(e => e.IsSuperAdmin).IsModified = false;

                        try
                        {
                            this._context.SaveChanges();
                        }
                        catch (DbUpdateConcurrencyException)
                        {
                            if (!this.UserExists(id))
                            {
                                return(this.NotFound());
                            }
                            else
                            {
                                throw;
                            }
                        }

                        return(this.NoContent());
                    }
                }
                catch (SecurityTokenExpiredException)
                {
                    return(new StatusCodeResult(StatusCodes.Status418ImATeapot));
                }
            }

            return(this.Unauthorized());
        }
Пример #7
0
        public ActionResult AddUser(User user)
        {
            /*var userName = Session["userName"] as string;

            userName = user.UserName;

            Session["userName"] = userName;*/
            HttpCookie userNameCookie = new HttpCookie(WebApplication1.Models.User.CoockieName);
            userNameCookie.Value = user.UserName;
            userNameCookie.Expires = DateTime.Now.AddHours(1);

            Response.Cookies.Add(userNameCookie);
            Request.Cookies[WebApplication1.Models.User.CoockieName].Value = userNameCookie.Value;
            return View("Definition", user);
        }
Пример #8
0
        /// <summary>
        /// 用户登录(BLL类):负责与界面层 、数据访问层的联系
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public static int sysLogin(User m)
        {
            string str = "adminValid"; //存储过程名称
            SqlParameter[] sqlParameter =
                {
                    //将UI层传递过来的用户名称和密码赋值给存储过程中的变量分别是adminUser和adminPwd(注意大小写)
                    new SqlParameter("@adminUser",SqlDbType.VarChar,20),
                    new SqlParameter("@adminPwd",SqlDbType.VarChar,20)
                };
            sqlParameter[0].Value = m.AdminUser;  //为参数指定值得来源
            sqlParameter[1].Value = m.AdminPwd;

            DAL d = new DAL();
            return int.Parse(d.ExecuteScalar(str, sqlParameter));//把存储过程名和参数传入
        }
Пример #9
0
        // [ValidateAntiForgeryToken]
        public IActionResult Create(Dictionary <string, string> d)
        //public IActionResult Create([Bind("Username,Password1, Password2")] Register r)
        {
            string user, p1, p2;

            d.TryGetValue("Username", out user);
            d.TryGetValue("Password1", out p1);
            d.TryGetValue("Password2", out p2);
            //return Ok(user + " "+ p1 + " " + p2);
            if (p1.Equals(p2) && !p1.Equals(""))   // if passwords match and is not null
            {
                User tempUser = new WebApplication1.Models.User(user, p1);
                //User temp = _context.Users.First(u => u.Username == user);

                try
                {
                    //if (temp != null)
                    //{
                    // ModelState.AddModelError("", "Username is not unique. " +
                    // "Try again with another username. ");
                    // }
                    // else
                    // {
                    //return Ok("!!!Pralindau pro kontrole!!!");
                    _context.Add(tempUser);
                    _context.SaveChanges();
                    //GlobalVariables.Users.Add(tempUser);
                    //return Ok("Uzregistravau!");
                    //userCreated = true;
                    //  }
                }
                catch (DbUpdateException /* ex */)
                {
                    //Log the error (uncomment ex variable name and write a log.
                    ModelState.AddModelError("", "Username is not unique. " +
                                             "Try again with another username. ");
                }
                //else
                //    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "The username is already taken." + "');", true);
            }
            //else
            //    MessageBox.Show("The passwords does not match!");
            //ATTENTION! the place to redirect might change
            return
                //Ok("ALEHANDER");
                (RedirectToAction("index", "user", "api/user/index/"));
            //Redirect(Request.QueryString["r"]);
        }
Пример #10
0
 public CharacterViewModel(
     Character Model
     )
 {
     CharacterID   = Model.CharacterID;
     ChartID       = Model.ChartID;
     UserID        = Model.UserID;
     UserData      = Model.UserData;
     Name          = Model.Name;
     AvatarImg     = Model.AvatarImg;
     Equipment     = Model.Equipment;
     Description   = Model.Description;
     Data          = Model.Data;
     Stats         = Model.Stats;
     Attributes    = Model.Attributes;
     Skills        = Model.Skills;
     IsDescription = Model.IsDescription;
     IsEquipment   = Model.IsEquipment;
 }
Пример #11
0
 public ActionResult Login(string userName, string passWord)
 {
     string message = "";
     int code = 0;
     User user = new User();
     user.AdminUser = userName;
     user.AdminPwd = passWord;
     if (BLL.sysLogin(user) > 0)
     {
         code = 1;
     }
     else
     {
             message = "用户名或密码 错误,请重新输入!";
             //code = 0;
     }
     // 以 json 格式返回数据
     JsonResult ajaxRes = new JsonResult();
     ajaxRes.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
     ajaxRes.Data = new { message = message, code = code };
     return ajaxRes;
 }
Пример #12
0
        // Konstruktor tworzący gotowy model. Dane pobiera zarówno z bazy danych, jak i z pliku
        // XML, dlatego warto upewnić się, że plik rzeczywiście istnieje.
        //
        // todo: Obsługa wyjątków w przypadku, gdy odczytywanie pliku nie powiedzie się:
        //       * ArgumentNullException    - gdy nie zostanie przekazana nazwa pliku (CharacterID)
        //       * FileNotFoundException    - gdy plik nie istnieje
        //       * NullReferenceException   - następstwo dwóch poprzednich, powstanie pusty obiekt,
        //                                    z którego będziemy próbowali odczytać dane
        /// <summary>Tworzy kompletny obiekt gracza zawierający wszystkie informacje</summary>
        /// <param name="characterDb">Model z danymi z bazy</param>
        public Character(
            CharacterDbModel characterDb
            )
        {
            // Przepisywanie danych do obiektu z bazy danych
            CharacterID = characterDb.CharacterID;
            ChartID     = characterDb.ChartID;
            UserID      = characterDb.UserID;
            Name        = characterDb.CharacterName;
            AvatarImg   = characterDb.AvatarImgSrc;

            // Uzupełnianie danych użytkownika, który stworzył gracza
            if (UserID != null)
            {
                UserData = new User(ApplicationDbContext.Create().Users.Find(UserID));
            }
            else UserData = null;

            // Odczytywanie pliku XML
            // UWAGA - Nie sprawdza, czy plik istnieje, możliwy wyjątek!
            XmlModels.Character characterXml = new XmlModels.Character(CharacterID);

            // Przepisywanie danych do obiektu z pliku XML
            Data            = DefaultMethods.ToDictionary(characterXml.Data);
            Stats           = DefaultMethods.ToDictionary(characterXml.Stat);
            Attributes      = DefaultMethods.ToDictionary(characterXml.Attribute);
            Skills          = DefaultMethods.ToDictionary(characterXml.Skill);
            if (characterXml.Equipment != null)
            Equipment   = characterXml.Equipment.ToArray();
            else
                Equipment   = null;
            if (characterXml.Description != null)
                Description = characterXml.Description.ToString();
            else
                Description = null;
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                // Create a local login before signing in the user
                var user = new User(model.UserName);
                var result = await IdentityManager.Users.CreateLocalUserAsync(user, model.Password);
                if (result.Success)
                {
                    await IdentityManager.Authentication.SignInAsync(AuthenticationManager, user.Id, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #14
0
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Manage");
            }
            
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                ClaimsIdentity id = await HttpContext.GetExternalIdentity();
                if (id == null)
                {
                    return View("ExternalLoginFailure");
                }
                try
                {
                    // Create a local user and sign in
                    var user = new User(model.UserName);
                    if (await Users.Create(user) &&
                        await Logins.Add(new UserLogin(user.Id, model.LoginProvider, id.FindFirstValue(ClaimTypes.NameIdentifier))))
                    {
                        await SignIn(user.Id, id.Claims, isPersistent: false);
                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        return View("ExternalLoginFailure");
                    }
                }
                catch (DbEntityValidationException e)
                {
                    ModelState.AddModelError("", e.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage);
                }
            }

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
Пример #15
0
 // Domyślny konstruktor, inicjalizuje pola Name oraz AvatarImg wartościami domyślnymi.
 // Alokuje pamięć dla pól definiowanych oraz dla pola Equipment.
 public Character()
 {
     CharacterID     = new Key(DefaultConstants.GeneratedCharacterKeyLength).Value;
     Name            = DefaultConstants.Character.DefaultCharacterName;
     AvatarImg       = DefaultConstants.Application.DefaultAvatarImgSource;
     Equipment       = new string[DefaultConstants.Character.DefaultEquipmentTableLength];
     Data            = new Dictionary<string, string>();
     Stats           = new Dictionary<string, int>();
     Attributes      = new Dictionary<string, int>();
     Skills          = new Dictionary<string, int>();
     UserData        = null;
     ChartID         = null;
     IsDescription   = false;
     IsEquipment     = false;
 }
Пример #16
0
 // Tworzy obiekt zawierający jedynie dane użytkownika. Oraz elementy zainicjalizowane
 // w domyślnym konstruktorze.
 /// <summary>Tworzy pusty model gracza zawierający dane o użytkowniku</summary>
 /// <param name="user">Obiekt zawierający dane użytkownika</param>
 public Character(
     ApplicationUser user
     ) : this()
 {
     // Gdyby jednak user był null
     if (user == null)
     {
         UserID = null;
         UserData = null;
     }
     else
     {
         // Przypisywanie wartości do pól
         UserID = user.Id;
         UserData = new User(ApplicationDbContext.Create().Users.Find(UserID));
     }
 }
Пример #17
0
        public async Task <IActionResult> PostUser([FromBody] UserWithPassword userWithPassword, [FromQuery] string apikey)
        {
            // Permission Level Everyone
            if (this.auth.KeyIsValid(apikey))
            {
                if (!this.ModelState.IsValid)
                {
                    return(this.BadRequest(this.ModelState));
                }

                var authProvider = new FirebaseAuthProvider(new FirebaseConfig(this.apikey));

                try
                {
                    var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(userWithPassword.Email, userWithPassword.Password);

                    var firebasetoken = authProvider.SignInWithEmailAndPasswordAsync(userWithPassword.Email, userWithPassword.Password).Result.FirebaseToken;
                    await this.firebase.SendVerificationEmail(firebasetoken);

                    // TODO check if usefull
                    if (auth.User == null)
                    {
                        return(this.BadRequest(this.ModelState));
                    }

                    User user = new User
                    {
                        Name      = userWithPassword.Name,
                        Surname   = userWithPassword.Surname,
                        Email     = userWithPassword.Email,
                        Birthday  = userWithPassword.Birthday,
                        CouncilID = userWithPassword.Council_id,
                        UID       = auth.User.LocalId,
                        Sex       = userWithPassword.Sex,
                        Address   = userWithPassword.Address,
                        Note      = userWithPassword.Note,
                    };

                    string token = this.jwtService.CreateKey(user.UID, user.CouncilID);
                    this.telBot.SendTextMessage($"User Created, Name: {user.Name} {user.Surname} ");
                    var userreturn = new
                    {
                        User     = user,
                        JwtToken = token
                    };
                    this._context.User.Add(user);
                    await this._context.SaveChangesAsync();

                    return(this.Ok(userreturn));

                    // return this.CreatedAtAction("GetUser", new { id = user.UID }, Tuple.Create(user, token));
                }

                // Catch Email Exists usw.
                catch (Exception e)
                {
                    this.telBot.SendTextMessage($"Error at USER CREATE with E-Mail: {userWithPassword.Email}");
                    // { "error": { "code": 400, "message": "EMAIL_EXISTS", "errors": [ { "message": "EMAIL_EXISTS", "domain": "global", "reason": "invalid" } ] } }
                    return(this.BadRequest(this.ModelState));
                }
            }

            return(this.Unauthorized());
        }