Esempio n. 1
0
        public IHttpActionResult PostBAIdentityUser(BAIdentityUser bAIdentityUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.Users.Add(bAIdentityUser);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException)
            {
                if (BAIdentityUserExists(bAIdentityUser.Id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtRoute("DefaultApi", new { id = bAIdentityUser.Id }, bAIdentityUser));
        }
Esempio n. 2
0
        public async Task <IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var info = await Authentication.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(InternalServerError());
            }

            var user = new BAIdentityUser()
            {
                UserName = model.Email, Email = model.Email
            };

            IdentityResult result = await UserManager.CreateAsync(user);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            result = await UserManager.AddLoginAsync(user.Id, info.Login);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }
            return(Ok());
        }
        public IHttpActionResult DeleteRoomReservations(int id)
        {
            RoomReservations roomReservations = db.RoomReservations.Find(id);

            if (roomReservations == null)
            {
                return(NotFound());
            }

            IdentityUser   user   = UserManager.FindById(User.Identity.GetUserId());
            BAIdentityUser baUser = new BAIdentityUser();

            baUser = user as BAIdentityUser;

            if (baUser == null)
            {
                return(null);
            }

            if (!baUser.appUserId.Equals(roomReservations.AppUserId))
            {
                return(Unauthorized());
            }

            db.RoomReservations.Remove(roomReservations);
            db.SaveChanges();

            return(Ok(roomReservations));
        }
Esempio n. 4
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            ApplicationUserManager userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            BAIdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.!!!!");
                return;
            }

            //if (!user.EmailConfirmed)
            //{
            //    context.SetError("invalid_grant", "AppUser did not confirm email.");
            //    return;
            //}

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            context.Validated(ticket);
        }
Esempio n. 5
0
        public IHttpActionResult PutBAIdentityUser(string id, BAIdentityUser bAIdentityUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != bAIdentityUser.Id)
            {
                return(BadRequest());
            }

            db.Entry(bAIdentityUser).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BAIdentityUserExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Esempio n. 6
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var roleHeader   = "Role";
            var userIDHeader = "appUserID";

            context.OwinContext.Response.Headers.Add("Access-Control-Expose-Headers", new[] { roleHeader, userIDHeader });

            ApplicationUserManager userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            BAIdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

            context.OwinContext.Response.Headers.Add(userIDHeader, new[] { user.appUserId.ToString() });

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.!!!!");
                return;
            }

            BAContext BAContext = new BAContext();
            var       userRole  = user.Roles.First().RoleId;
            var       role      = BAContext.Roles.FirstOrDefault(r => r.Id == userRole);

            //BAContext.Roles.Where(x =>
            //bool isAdmin = await userManager.IsInRoleAsync(user.UserName, "Admin");



            if (role.Name.Equals("Admin"))
            {
                context.OwinContext.Response.Headers.Add("Role", new[] { "Admin" });
            }
            else if (role.Name.Equals("Manager"))
            {
                context.OwinContext.Response.Headers.Add("Role", new[] { "Manager" });
            }
            else
            {
                context.OwinContext.Response.Headers.Add("Role", new[] { "User" });
            }


            //if (!user.EmailConfirmed)
            //{
            //    context.SetError("invalid_grant", "AppUser did not confirm email.");
            //    return;
            //}

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            context.Validated(ticket);
        }
Esempio n. 7
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            ApplicationUserManager userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            BAIdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.!!!!");
                return;
            }

            DBContext db       = new DBContext();
            var       userRole = user.Roles.FirstOrDefault();
            var       role     = db.Roles.SingleOrDefault(r => r.Id == userRole.RoleId);
            var       roleName = role?.Name;

            if (roleName == "Admin")
            {
                context.OwinContext.Response.Headers.Add("Role", new[] { "Admin" });
            }
            else if (roleName == "User")
            {
                context.OwinContext.Response.Headers.Add("Role", new[] { "User" });
            }


            context.OwinContext.Response.Headers.Add("Access-Control-Expose-Headers", new[] { "Role", "user_id" });
            context.OwinContext.Response.Headers.Add("user_id", new[] { user.Id });


            /*   AppUser appUser = new AppUser();
             * var userId = user.AppUserId;
             *
             * if(userId.Equals(appUser.Id))
             * {
             *     context.OwinContext.Response.Headers.Add("Id", new[] { "userID" });
             * }
             *
             *
             * //if (!user.EmailConfirmed)
             * //{
             * //    context.SetError("invalid_grant", "AppUser did not confirm email.");
             * //    return;
             * //}
             * //var identity = new ClaimsIdentity(context.Options.AuthenticationType);
             * //identity.AddClaim(new Claim("sub", context.UserName));
             * //identity.AddClaim(new Claim("role", "user"));*/
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            context.Validated(ticket);
        }
        public IHttpActionResult m3(int id, Accommodation accommodation)
        {
            IdentityUser   user   = UserManager.FindById(User.Identity.GetUserId());
            BAIdentityUser baUser = new BAIdentityUser();

            baUser = user as BAIdentityUser;

            if (baUser == null)
            {
                return(null);
            }

            var userRole = baUser.Roles.FirstOrDefault().RoleId;
            var roleName = db.Roles.FirstOrDefault(a => a.Id == userRole);

            if (!roleName.Name.Equals("Manager"))
            {
                return(Unauthorized());
            }

            if (!baUser.appUserId.Equals(accommodation.AppUserId))
            {
                return(Unauthorized());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != accommodation.Id)
            {
                return(BadRequest());
            }

            db.Entry(accommodation).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AccommodationExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Esempio n. 9
0
        public IHttpActionResult GetBAIdentityUser(string id)
        {
            BAIdentityUser bAIdentityUser = db.Users.Find(id);

            if (bAIdentityUser == null)
            {
                return(NotFound());
            }

            return(Ok(bAIdentityUser));
        }
Esempio n. 10
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            ApplicationUserManager userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            BAIdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.!!!!");
                return;
            }

            BAContext db = new BAContext();

            var userRole = user.Roles.FirstOrDefault();
            var role     = db.Roles.SingleOrDefault(r => r.Id == userRole.RoleId);
            var roleName = role?.Name;

            if (roleName == "Admin")
            {
                context.OwinContext.Response.Headers.Add("Role", new[] { "Admin" });
            }
            else if (roleName == "Manager")
            {
                context.OwinContext.Response.Headers.Add("Role", new[] { "Manager" });
            }
            else
            {
                context.OwinContext.Response.Headers.Add("Role", new[] { "User" });
            }

            //Mora se dodati u header response-a kako bi se se Role atribut
            //mogao procitati na klijentskoj strani
            context.OwinContext.Response.Headers.Add("Access-Control-Expose-Headers", new[] { "Role", "user_id" });
            context.OwinContext.Response.Headers.Add("user_id", new[] { user.Id });
            //if (!user.EmailConfirmed)
            //{
            //    context.SetError("invalid_grant", "AppUser did not confirm email.");
            //    return;
            //}

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            var ticket = new AuthenticationTicket(oAuthIdentity, null);



            context.Validated(ticket);
        }
Esempio n. 11
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            BAIdentityUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                                                                                externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

            return(Ok());
        }
Esempio n. 12
0
        public IHttpActionResult DeleteBAIdentityUser(string id)
        {
            BAIdentityUser bAIdentityUser = db.Users.Find(id);

            if (bAIdentityUser == null)
            {
                return(NotFound());
            }

            db.Users.Remove(bAIdentityUser);
            db.SaveChanges();

            return(Ok(bAIdentityUser));
        }
Esempio n. 13
0
        public IHttpActionResult m3(int id, Room room)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != room.Id)
            {
                return(BadRequest());
            }

            IdentityUser   user   = UserManager.FindById(User.Identity.GetUserId());
            BAIdentityUser baUser = new BAIdentityUser();

            baUser = user as BAIdentityUser;

            if (baUser == null)
            {
                return(null);
            }

            Accommodation acc = db.Accommodations.FirstOrDefault(a => a.Id == room.AccommodationId);

            if (!baUser.appUserId.Equals(acc.AppUserId))
            {
                return(Unauthorized());
            }

            db.Entry(room).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RoomExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Esempio n. 14
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            try
            {
                app_User1 = new AppUser()
                {
                    UserName = model.UserName
                };
                db.AppUsers.Add(app_User1);
                db.SaveChanges();
            }
            catch (Exception e)
            {
            }

            var userStore   = new UserStore <BAIdentityUser>(db);
            var userManager = new UserManager <BAIdentityUser>(userStore);

            BAIdentityUser user = new BAIdentityUser();

            user.UserName     = model.UserName;
            user.Email        = model.Email;
            user.PasswordHash = BAIdentityUser.HashPassword(model.Password);
            user.AppUserId    = app_User1.Id;
            //{
            //    UserName = model.UserName,
            //    Email = model.Email,
            //    PasswordHash = BAIdentityUser.HashPassword(model.Password),
            //    AppUserId = app_User1.Id
            //};


            userManager.Create(user);
            userManager.AddToRole(user.Id, model.Role);



            return(Ok());
        }
Esempio n. 15
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new BAIdentityUser()
            {
                UserName = model.Email, Email = model.Email
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
        public IHttpActionResult DeleteAccommodation(int id)
        {
            Accommodation accommodation = db.Accommodations.Find(id);

            if (accommodation == null)
            {
                return(NotFound());
            }

            IdentityUser   user   = UserManager.FindById(User.Identity.GetUserId());
            BAIdentityUser baUser = new BAIdentityUser();

            baUser = user as BAIdentityUser;

            if (baUser == null)
            {
                return(null);
            }

            var userRole = baUser.Roles.FirstOrDefault().RoleId;
            var roleName = db.Roles.FirstOrDefault(a => a.Id == userRole);

            if (!roleName.Name.Equals("Manager"))
            {
                return(Unauthorized());
            }

            if (!baUser.appUserId.Equals(accommodation.AppUserId))
            {
                return(Unauthorized());
            }

            db.Accommodations.Remove(accommodation);

            db.Comments.RemoveRange(db.Comments.Where(a => a.AccommodationId == id));
            db.Rooms.RemoveRange(db.Rooms.Where(a => a.AccommodationId == id));
            db.SaveChanges();

            return(Ok(accommodation));
        }
Esempio n. 17
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        //public IHttpActionResult Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            AppUser appUser = new AppUser()
            {
                Name = model.Name, LastName = model.LastName
            };
            string BaIdentityUserId = Guid.NewGuid().ToString();
            var    user             = new BAIdentityUser()
            {
                Id = BaIdentityUserId, UserName = model.Email, Email = model.Email, AppUser = appUser, PasswordHash = BAIdentityUser.HashPassword(model.Password)
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            //IdentityResult result = UserManager.Create(user);

            if (!result.Succeeded)
            {
                return(BadRequest("Username is already taken by another user."));
                //return GetErrorResult(result);
            }

            UserManager.AddToRole(BaIdentityUserId, model.Role);

            return(Ok());


            /*
             *      if (!context.Users.Any(u => u.UserName == "admin"))
             *      {
             *          var user = new BAIdentityUser() { Id = "admin", UserName = "******", Email = "*****@*****.**", PasswordHash = BAIdentityUser.HashPassword("admin") };
             *          userManager.Create(user);
             *          userManager.AddToRole(user.Id, "Admin");
             *      }*/
        }
Esempio n. 18
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            BAContext context = new BAContext();

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            AppUser _appUser = new AppUser(model.Name + " " + model.Lastname);

            context.AppUsers.AddOrUpdate(a => a.FullName, _appUser);
            ContextHelper.SaveChanges(context);

            //var user = new BAIdentityUser() { UserName = model.Email, Email = model.Email };
            var user = new BAIdentityUser(model.Username, model.Password, model.Email)
            {
                appUserId = _appUser.Id
            };

            var userStore   = new UserStore <BAIdentityUser>(context);
            var userManager = new UserManager <BAIdentityUser>(userStore);

            userManager.Create(user);
            // proveriti ovde, ili na klijentu, da li je rola validna
            userManager.AddToRole(user.Id, model.Role);

            //IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            // kako god napravila password, ovde pada, ne bude succeded, i nikad nije dobra sifra =.=
            // treba napraviti ako ovde padne, da se onaj AppUser brise iz baze sto je napravljen gore
            //if (!result.Succeeded)
            //{
            //    return GetErrorResult(result);
            //}

            return(Ok());
        }
Esempio n. 19
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            BAContext db = new BAContext();

            db.AppUsers.Add(new AppUser()
            {
                UserName = model.Username, FullName = model.Name + " " + model.Surname
            });

            db.SaveChanges();

            var appUser = db.AppUsers.FirstOrDefault(p => p.UserName == model.Username);

            if (appUser == null)
            {
                return(NotFound());
            }

            var user = new BAIdentityUser()
            {
                UserName = model.Username, Email = model.Email, Id = model.Username, appUserId = appUser.Id
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
Esempio n. 20
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            /*if (!ModelState.IsValid)
             * {
             *  return BadRequest(ModelState);
             * }*/
            BookingApp.Models.BAContext context = new BAContext();

            //var userStore = new UserStore<BAIdentityUser>(context);
            //var userManager = new UserManager<BAIdentityUser>(userStore);

            AppUser apuser = new AppUser {
                Name = model.Username, Lastname = model.Lastname
            };

            context.AppUsers.Add(apuser);
            context.SaveChanges();

            string guidId = Guid.NewGuid().ToString();
            var    user   = new BAIdentityUser()
            {
                Id = guidId, UserName = model.Username, Email = model.Email, PasswordHash = BAIdentityUser.HashPassword(model.Password), appUserId = apuser.Id
            };

            IdentityResult result = await UserManager.CreateAsync(user);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            //UserManager.Create(user);
            //UserManager.AddToRole(user.Id, model.Role);

            UserManager.AddToRole(user.Id, model.Role);

            return(Ok());
        }
Esempio n. 21
0
        public IHttpActionResult PostAppUser(AppUser appUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            if (!db.Users.Any(u => u.UserName == appUser.Username))
            {
                var user = new BAIdentityUser()
                {
                    UserName = appUser.Username, Email = appUser.Email, PasswordHash = BAIdentityUser.HashPassword(appUser.Password)
                };

                db.Users.Add(user);
                db.SaveChanges();
            }



            return(CreatedAtRoute("DefaultApi", new { id = appUser.Id }, appUser));
        }
Esempio n. 22
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            BookingApp.Models.BAContext context = new BAContext();

            AppUser appUser = new AppUser()
            {
                Name = model.Name, Surname = model.Surname
            };

            var user = new BAIdentityUser()
            {
                Id = Guid.NewGuid().ToString(), UserName = model.Email, Email = model.Email, appUser = appUser, PasswordHash = BAIdentityUser.HashPassword(model.Password)
            };

            var userStore = new UserStore <BAIdentityUser>(context);

            var userManager = new UserManager <BAIdentityUser>(userStore);

            userManager.Create(user);
            userManager.AddToRole(user.Id, model.Role);

            return(Ok());
        }
Esempio n. 23
0
        public IHttpActionResult PostRoom(Room room)
        {
            IdentityUser   user   = UserManager.FindById(User.Identity.GetUserId());
            BAIdentityUser baUser = new BAIdentityUser();

            baUser = user as BAIdentityUser;

            if (baUser == null)
            {
                return(null);
            }

            var role  = db.Roles.Where(r => r.Name.Equals("Manager")).FirstOrDefault();
            var users = role.Users.Join(db.Users, u1 => u1.UserId, u2 => u2.Id, (u1, u2)
                                        => new { UserRole = u1, User = u2 }).Select(x => x.User.appUserId).Join(db.AppUsers, u3 => u3, u4 => u4.Id, (u3, u4) => new { AppUser = u4 }).ToList();

            foreach (var us in users)
            {
                if (baUser.appUserId.Equals(us.AppUser.Id))
                {
                    if (us.AppUser.Baned)
                    {
                        return(Unauthorized());
                    }
                }
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.Rooms.Add(room);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { controller = "Room", id = room.Id }, room));
        }
        public IHttpActionResult DeleteComment(int id, int ida)
        {
            Comment comment = db.Comments.Find(id, ida);

            if (comment == null)
            {
                return(NotFound());
            }

            IdentityUser   user   = UserManager.FindById(User.Identity.GetUserId());
            BAIdentityUser baUser = new BAIdentityUser();

            baUser = user as BAIdentityUser;

            if (baUser == null)
            {
                return(null);
            }

            var userRole = baUser.Roles.FirstOrDefault().RoleId;
            var roleName = db.Roles.FirstOrDefault(a => a.Id == userRole);

            if (!roleName.Name.Equals("AppUser"))
            {
                return(Unauthorized());
            }

            if (!baUser.appUserId.Equals(comment.AppUserId))
            {
                return(Unauthorized());
            }

            db.Comments.Remove(comment);
            db.SaveChanges();

            return(Ok(comment));
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            BAIdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Esempio n. 26
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                var allowedOrigin = "*";
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

                var roleHeader     = "Role";
                var userIdHeader   = "UserId";
                var userNameHeader = "UserName";
                context.OwinContext.Response.Headers.Add("Access-Control-Expose-Headers", new[] { roleHeader, userIdHeader, userNameHeader });

                ApplicationUserManager userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

                BAIdentityUser user = await userManager.FindAsync(context.UserName, context.Password);


                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.!!!!");
                    return;
                }

                BAContext BAContext = new BAContext();
                var       userRole  = user.Roles.First().RoleId;
                var       role      = BAContext.Roles.FirstOrDefault(r => r.Id == userRole);

                //BAContext.Roles.Where(x =>
                //bool isAdmin = await userManager.IsInRoleAsync(user.UserName, "Admin");



                if (role.Name.Equals("Admin"))
                {
                    context.OwinContext.Response.Headers.Add("Role", new[] { "Admin" });
                }
                else if (role.Name.Equals("Manager"))
                {
                    context.OwinContext.Response.Headers.Add("Role", new[] { "Manager" });
                }
                else
                {
                    context.OwinContext.Response.Headers.Add("Role", new[] { "User" });
                }

                context.OwinContext.Response.Headers.Add("UserId", new[] { user.AppUserId.ToString() });


                if (role.Name.Equals("Admin"))
                {
                    string username = "******" + user.Email;
                    context.OwinContext.Response.Headers.Add("UserName", new[] { username });
                }
                else
                {
                    AppUser appUser  = BAContext.AppUsers.Where(au => au.Id == user.AppUserId).FirstOrDefault();
                    string  username = role.Name + ": " + appUser.Name + " " + appUser.LastName;
                    context.OwinContext.Response.Headers.Add("UserName", new[] { username });
                }

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

                var ticket = new AuthenticationTicket(oAuthIdentity, null);

                context.Validated(ticket);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Esempio n. 27
0
        protected override void Seed(BookingApp.Models.BAContext context)
        {
            /****/

            if (!context.Roles.Any(r => r.Name == "Admin"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "Admin"
                };

                manager.Create(role);
            }

            if (!context.Roles.Any(r => r.Name == "Manager"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "Manager"
                };

                manager.Create(role);
            }

            if (!context.Roles.Any(r => r.Name == "AppUser"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "AppUser"
                };

                manager.Create(role);
            }


            var userStore   = new UserStore <BAIdentityUser>(context);
            var userManager = new UserManager <BAIdentityUser>(userStore);

            if (!context.Users.Any(u => u.UserName == "mitja"))
            {
                var user1 = new BAIdentityUser()
                {
                    Id = "mitja", UserName = "******", Email = "*****@*****.**", PasswordHash = BAIdentityUser.HashPassword("mitja")
                };
                userManager.Create(user1);
                userManager.AddToRole(user1.Id, "Admin");
            }

            BAIdentityUser user = new BAIdentityUser()
            {
                Id = "stefan", UserName = "******", Email = "*****@*****.**", PasswordHash = BAIdentityUser.HashPassword("stefan")
            };

            if (!context.Users.Any(u => u.UserName == "stefan"))
            {
                userManager.Create(user);
                userManager.AddToRole(user.Id, "Manager");
            }

            if (!context.Users.Any(u => u.UserName == "user"))
            {
                var user1 = new BAIdentityUser()
                {
                    Id = "user", UserName = "******", Email = "*****@*****.**", PasswordHash = BAIdentityUser.HashPassword("user")
                };
                userManager.Create(user1);
                userManager.AddToRole(user1.Id, "AppUser");
            }

            user.Accomodations    = new List <Accommodation>();
            user.Comments         = new List <Comment>();
            user.RoomReservations = new List <RoomReservations>();



            var accomod  = new Accommodation();
            var accomod2 = new Accommodation();
            var accomods = new List <Accommodation>()
            {
                accomod, accomod2
            };

            var accomType = new AccommodationType();

            accomType.Name = "Motel";
            // accomType.Accommodations = accomods;

            var accomType2 = new AccommodationType();

            accomType2.Name = "Hotel";
            // accomType2.Accommodations = accomods;

            var place  = new Place();
            var place2 = new Place();

            var room  = new Room();
            var room2 = new Room();
            var rooms = new List <Room>()
            {
                room, room2
            };

            var country = new Country();

            country.Name = "Serbia";
            //country.Regions = new List<Region>() { region, region2 };
            country.Code = 43;
            //region.Country = country;

            var country2 = new Country();

            country2.Name = "Serbia";
            //country2.Regions = new List<Region>() { region2 };
            country2.Code = 44;
            //region2.Country = country2;


            var region = new Region();

            region.Name    = "Zlatibor";
            region.Country = country;
            //region.Places = new List<Place>() { place, place2 };

            var region2 = new Region();

            region2.Name    = "Jahorina";
            region2.Country = country2;
            // region2.Places = new List<Place>() { place, place2 };

            place.Name     = "place1";
            place.RegionId = 1;
            //place.Accommodations = new List<Accommodation>() { accomod, accomod2 };

            place2.Name     = "place2";
            place2.RegionId = 1;
            //place2.Accommodations = new List<Accommodation>() { accomod, accomod2 };

            accomod.Address  = "Jovana Subotica";
            accomod.Approved = true;
            accomod.User     = user;
            //accomod.Comments = comments;
            accomod.AvrageGrade      = 50;
            accomod.Description      = "opisAccom";
            accomod.AccomodationType = accomType;
            accomod.ImageURL         = "http://arhiva.alo.rs/resources/img/10-07-2014/single_news/1300330-sako1.jpg";
            accomod.Latitude         = 41.9271155;
            accomod.Longitude        = 19.2364064;
            accomod.Place            = place;
            accomod.Name             = "Vila Rijana";
            //accomod.Rooms = rooms;

            accomod2.Address  = "Nikole Pasica";
            accomod2.Approved = true;
            accomod2.User     = user;
            //accomod2.Comments = comments;
            accomod2.AvrageGrade      = 40;
            accomod2.Description      = "opisAccom2";
            accomod2.AccomodationType = accomType2;
            accomod2.ImageURL         = "https://s-ec.bstatic.com/images/hotel/max1024x768/741/74116567.jpg";
            accomod2.Latitude         = 42.286238;
            accomod2.Longitude        = 18.8327733;
            accomod2.Place            = place2;
            accomod2.Name             = "Hotel Moskva";
            //accomod.Rooms = rooms;

            var comment = new Comment()
            {
                User = user, Text = "dobar", Grade = 10, Accomodation = accomod
            };
            var comment2 = new Comment()
            {
                User = user, Text = "los", Grade = 2, Accomodation = accomod2
            };

            room.Description   = "opisSobe1";
            room.PricePerNight = 100;
            room.RoomNumber    = 4;
            room.BedCount      = 3;
            room.Accomodation  = accomod;
            //room.RoomReservations = new List<RoomReservations>() { roomReservations, roomReservations2 };

            room2.Description   = "opisSobe12";
            room2.PricePerNight = 97;
            room2.RoomNumber    = 6;
            room2.BedCount      = 3;
            room2.Accomodation  = accomod2;
            //room2.RoomReservations = new List<RoomReservations>() { roomReservations, roomReservations2 };

            var roomReservations  = new RoomReservations();
            var roomReservations2 = new RoomReservations();

            roomReservations.Room      = room;
            roomReservations.User      = user;
            roomReservations.Timestamp = DateTime.Now.ToString();
            roomReservations.StartDate = new DateTime(2017, 1, 1).ToString();
            roomReservations.EndDate   = new DateTime(2017, 2, 2).ToString();

            roomReservations2.Room      = room2;
            roomReservations2.User      = user;
            roomReservations2.Timestamp = DateTime.Now.ToString();
            roomReservations2.StartDate = new DateTime(2017, 3, 3).ToString();
            roomReservations2.EndDate   = new DateTime(2017, 4, 4).ToString();

            context.Accommodations.AddOrUpdate(accomod);
            context.Accommodations.AddOrUpdate(accomod2);

            // context.Users
            context.Rooms.AddOrUpdate(room);
            context.Rooms.AddOrUpdate(room2);

            context.RoomReservationss.AddOrUpdate(roomReservations);
            context.RoomReservationss.AddOrUpdate(roomReservations2);

            context.Comments.AddOrUpdate(comment);
            context.Comments.AddOrUpdate(comment2);

            context.SaveChanges();
        }
Esempio n. 28
0
        protected override void Seed(BookingApp.Models.BAContext context)
        {
            System.Diagnostics.Debug.WriteLine("\n__________________________________\nConfiguration.Seed() debug:\n");

            #region Creating Roles
            if (!context.Roles.Any(r => r.Name == "Admin"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "Admin"
                };

                manager.Create(role);
            }

            if (!context.Roles.Any(r => r.Name == "Manager"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "Manager"
                };

                manager.Create(role);
            }

            if (!context.Roles.Any(r => r.Name == "AppUser"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "AppUser"
                };

                manager.Create(role);
            }
            #endregion

            // First, we have to add independent entities, then call context.SaveChanges() and then add dependent...

            // AppUser ima samo fullname i auto-generatedId
            // preko kog se povezuje sa BAIdentityUsero-om
            // BAIdentityUser ima informaciju o odgovarajucem AppUser-u
            // kao metode za generisanje Identita i hash pasworda, nasledjen je iz IdentityUser-a
            // IdentityUser sadrzi polja kao sto je password, username, email, roles
            // AspeNetUsers tabela sadrzi BAIdentityUser-e
            // AppUsers tabela su jednostavni korisnici koji mi pravimo

            #region Adding Users

            context.AppUsers.AddOrUpdate(
                p => p.FullName,
                new AppUser()
            {
                FullName = "Admin Adminovic"
            }
                );
            context.AppUsers.AddOrUpdate(
                p => p.FullName,
                new AppUser()
            {
                FullName = "Menadzer Menadzerovic"
            }
                );
            context.AppUsers.AddOrUpdate(
                p => p.FullName,
                new AppUser()
            {
                FullName = "Zvezdana Menadzerovic"
            }
                );
            context.AppUsers.AddOrUpdate(
                p => p.FullName,
                new AppUser()
            {
                FullName = "Miljana Menadzerovic"
            }
                );

            context.AppUsers.AddOrUpdate(
                p => p.FullName,
                new AppUser()
            {
                FullName = "AppUser AppUserovic"
            }
                );

            ContextHelper.SaveChanges(context);

            // neautentikovanog korisnika ne pravimo,
            // to je bilo ko, ko pristupi, a da nije u rolama?
            #endregion

            #region Associating users with roles

            var userStore   = new UserStore <BAIdentityUser>(context);
            var userManager = new UserManager <BAIdentityUser>(userStore);

            var     us = context.Users.FirstOrDefault();
            AppUser _appUser;

            // adding data to AspNetUsers table  -> context.Users
            // model entiteta u toj tabeli je IndentityUser odnosno BAIdentityUser
            // kljuc tabele je Id tipa string, dakle ne autogenerated
            if (!context.Users.Any(u => u.UserName == "admin"))
            {
                _appUser = context.AppUsers.FirstOrDefault(a => a.FullName == "Admin Adminovic");

                var user = new BAIdentityUser()
                {
                    Id           = "admin",
                    UserName     = "******",
                    Email        = "*****@*****.**",
                    PasswordHash = BAIdentityUser.HashPassword("admin"),
                    appUserId    = _appUser.Id // navigation
                };
                userManager.Create(user);
                userManager.AddToRole(user.Id, "Admin");
            }

            if (!context.Users.Any(u => u.UserName == "manager"))
            {
                _appUser = context.AppUsers.FirstOrDefault(a => a.FullName == "Menadzer Menadzerovic");
                var user = new BAIdentityUser()
                {
                    Id           = "manager",
                    UserName     = "******",
                    Email        = "*****@*****.**",
                    PasswordHash = BAIdentityUser.HashPassword("manager"),
                    appUserId    = _appUser.Id // navigation
                };
                userManager.Create(user);
                userManager.AddToRole(user.Id, "Manager");
            }

            if (!context.Users.Any(u => u.UserName == "appu"))
            {
                _appUser = context.AppUsers.FirstOrDefault(a => a.FullName == "AppUser AppUserovic");
                var user = new BAIdentityUser()
                {
                    Id           = "appu",
                    UserName     = "******",
                    Email        = "*****@*****.**",
                    PasswordHash = BAIdentityUser.HashPassword("appu"),
                    appUserId    = _appUser.Id // navigation
                };
                userManager.Create(user);
                userManager.AddToRole(user.Id, "AppUser");
            }

            // pravljenje nasih usera i asociranje istih sa rolama
            // buduci da je Id string, vodicemo se konvencijom da je vrenost Id = vrednost UserName + "Id"
            // dodala sam konstruktor pa pogledaj

            // ovo je query koji pozvezuje sve potrebne podatke o useru

            // select UserId as 'AspNetUserRoles.UserId',RoleId as'AspNetUserRoles.RoleId',
            // AspNetRoles.Name as 'AspNetRoles.roleName', appUserId as 'AspNetUsers.appUserId', UserName
            // from AspNetUserRoles, AspNetRoles, AspNetUsers where AspNetRoles.Id = AspNetUserRoles.RoleId
            // and AspNetUsers.Id = AspNetUserRoles.UserId

            //_appUser = context.AppUsers.FirstOrDefault(a => a.FullName == "Miljana Menadzerovic");
            //var BAIdUser = new BAIdentityUser("miki", "miki123", "*****@*****.**") { appUserId = _appUser.Id };
            //userManager.Create(BAIdUser);
            //userManager.AddToRole(BAIdUser.Id, "Manager");

            //_appUser = context.AppUsers.FirstOrDefault(a => a.FullName == "Zvezdana Menadzerovic");
            //BAIdUser = new BAIdentityUser("zvezda", "zvezda123", "*****@*****.**") { appUserId = _appUser.Id };
            //userManager.Create(BAIdUser);
            //userManager.AddToRole(BAIdUser.Id, "Manager");


            //ContextHelper.SaveChanges(context);
            #endregion

            #region Adding Countries, Regions and Places

            var countries = new List <Country>()
            {
                new Country()
                {
                    Name = "Serbia", Code = "SRB"
                },
                new Country()
                {
                    Name = "Macedonia", Code = "MCD"
                },
                new Country()
                {
                    Name = "Australia", Code = "ASTRL"
                },
                new Country()
                {
                    Name = "Norway", Code = "NRWY"
                },
                new Country()
                {
                    Name = "Cuba", Code = "CBA"
                }
            };
            context.Countries.AddOrUpdate(c => c.Code, countries.ToArray());
            ContextHelper.SaveChanges(context); // moramo da uradimo da bi se generisao Id


            var regions = new List <Region>()
            {
                new Region()
                {
                    Name = "Backa", CountryId = countries[0].Id
                },
                new Region()
                {
                    Name = "Srem", CountryId = countries[0].Id
                },
                new Region()
                {
                    Name = "Banat", CountryId = countries[0].Id
                },

                new Region()
                {
                    Name = "Vardar", CountryId = countries[1].Id
                },

                new Region()
                {
                    Name = "New South Wales", CountryId = countries[2].Id
                },
                new Region()
                {
                    Name = "Victoria", CountryId = countries[2].Id
                },

                new Region()
                {
                    Name = "Hedmark", CountryId = countries[3].Id
                },
                new Region()
                {
                    Name = "Vestfold", CountryId = countries[3].Id
                },

                new Region()
                {
                    Name = "La Habana", CountryId = countries[4].Id
                },
            };

            context.Regions.AddOrUpdate(r => new { r.Name, r.CountryId }, regions.ToArray());
            ContextHelper.SaveChanges(context);

            // ovo ne moramo raditi, jer se automatski dodele regioni kad im dodelimo id drzave
            // countries[0].Regions.Add(regions[0]); // i tako za sve ostale regione


            // ako regione dodamo kao child objekte na objekat koji je vec u bazi, u ovom slucaju
            // sledeci put kad uradimo SaveChanges, oni ce se dodati u odgovarajucu tabelu u bazi
            // to znaci da ako imamo country C1 i region R1, ako je C1 vec dodata u bazu,
            // mozemo da uradimo C1.Regions.Add(R1) ili context.Regions.Add(R1)


            var places = new List <Place>()
            {
                new Place()
                {
                    Name = "Temerin", RegionId = regions[0].Id
                },                                                   // backa
                new Place()
                {
                    Name = "Novi Sad", RegionId = regions[0].Id
                },

                new Place()
                {
                    Name = "Sremski Karlovci", RegionId = regions[1].Id
                },                                                            // srem

                new Place()
                {
                    Name = "Zrenjanin", RegionId = regions[2].Id
                },                                                     // banat


                new Place()
                {
                    Name = "Veles", RegionId = regions[3].Id
                },                                                 // vardar


                new Place()
                {
                    Name = "Sydney", RegionId = regions[4].Id
                },                                                  //NSW

                new Place()
                {
                    Name = "Melbourne", RegionId = regions[5].Id
                },                                                     // victoria


                new Place()
                {
                    Name = "Hamar", RegionId = regions[6].Id
                },                                                 // hedmark

                new Place()
                {
                    Name = "Tensberg", RegionId = regions[7].Id
                },                                                    // vestfold


                new Place()
                {
                    Name = "Havana", RegionId = regions[8].Id
                },                                                  // la habana
            };

            context.Places.AddOrUpdate(p => new { p.Name, p.RegionId }, places.ToArray());
            ContextHelper.SaveChanges(context);
            // sada su automatski povezani mesta sa odgovarajucim regionima, tj. region.places vise nije prazno
            // ne moramo mi to rucno da popunjavamo

            // nakon ovako dodatih podataka, ako izbrises countries (delete from table dbo.Countries u sql menageru), brisu se i regije i places
            // nisam probala kroz entity framework api da brisem i modifikujem...

            #endregion

            #region Adding AccomodationTypes and Accomodations

            var accTypes = new List <AccommodationType>()
            {
                new AccommodationType()
                {
                    Name = "Hotel"
                },
                new AccommodationType()
                {
                    Name = "Hostel"
                },
                new AccommodationType()
                {
                    Name = "Private Home"
                },
                new AccommodationType()
                {
                    Name = "Boutique hotel"
                },
                new AccommodationType()
                {
                    Name = "Cottage"
                }
            };
            context.AccomodationTypes.AddOrUpdate(at => at.Name, accTypes.ToArray());
            ContextHelper.SaveChanges(context);


            /*Ovako, buduci da OwnerId treba da bude Id postojeceg usera, pretpostavljam menadzera, ja sam pokusala da
             * naprvim vise usera sa rolom menadzera, ali mi to nesto nije poslo za rukom, jer su oni nesot komplikovali da je username=roleid, svasta nesto
             * pa svuda stavljam jednog istog ownera
             *
             * Uglavnom, moramo videti sta cemo za te usere, nemam sad zivaca da se batrgam oko toga
             */

            var owner = context.Users.Where(u => u.Id == "manager").FirstOrDefault();

            var accoms = new List <Accomodation>()
            {
                // novi sad
                new Accomodation()
                {
                    Name = "Hotel Park",
                    AccomodationTypeId = accTypes[0].Id,
                    PlaceId            = places[1].Id,
                    OwnerId            = owner.appUserId,
                    Latitude           = 45.26714,
                    Longitude          = 19.8,
                    AverageGrade       = 4.5,
                    Approved           = true,
                    Description        = "Great hotel", //lako cemo promeniti ovaj opis, samo da pise nesto sad
                    Address            = "Novosadskog sajma 35",
                    //ImageUrl="~Content/Images/hotelPark.jpg"  // na ovoj lokaciji ce biti slike
                    ImageUrl = "hotelPark.jpg"
                },
                new Accomodation()
                {
                    Name = "Hotel Prezident",
                    AccomodationTypeId = accTypes[0].Id,
                    PlaceId            = places[1].Id,
                    OwnerId            = owner.appUserId,
                    Latitude           = 45.26714,
                    Longitude          = 19.85,
                    AverageGrade       = 3.8,
                    Approved           = true,
                    Description        = "Very good",
                    Address            = "Futoska 109"
                },

                new Accomodation()
                {
                    Name = "City Hostel",
                    AccomodationTypeId = accTypes[1].Id,
                    PlaceId            = places[1].Id,
                    OwnerId            = owner.appUserId,
                    Latitude           = 45.26714,
                    Longitude          = 19.83355,
                    AverageGrade       = 2.5,
                    Approved           = true,
                    Description        = "Nice hostel",
                    Address            = "Radnicka 21"
                },

                // karlovci
                new Accomodation()
                {
                    Name = "Premier Prezident",
                    AccomodationTypeId = accTypes[0].Id,
                    PlaceId            = places[2].Id,
                    OwnerId            = owner.appUserId,
                    Latitude           = 45.2025,
                    Longitude          = 19.93444,
                    AverageGrade       = 4.2,
                    Description        = "Great",
                    Address            = "Karadjordjeva 2"
                },
                new Accomodation()
                {
                    Name = "Apartman Zeravica",
                    AccomodationTypeId = accTypes[2].Id,
                    PlaceId            = places[2].Id,
                    OwnerId            = owner.appUserId,
                    Latitude           = 45.2025,
                    Longitude          = 19.9,
                    AverageGrade       = 3,
                    Approved           = true,
                    Description        = "Very nice",
                    Address            = "Brace Dejanovic 7"
                },

                // sidnej :)
                new Accomodation()
                {
                    Name = "Hotel Hilton",
                    AccomodationTypeId = accTypes[0].Id,
                    PlaceId            = places[5].Id,
                    OwnerId            = owner.appUserId,
                    Latitude           = -33.86749,
                    Longitude          = 151.20699,
                    AverageGrade       = 5,
                    Description        = "The best hotel",
                    Address            = "488 George St"
                },
                new Accomodation()
                {
                    Name = "The Glebe",
                    AccomodationTypeId = accTypes[2].Id,
                    PlaceId            = places[5].Id,
                    OwnerId            = owner.appUserId,
                    Latitude           = -33.86749,
                    Longitude          = 151,
                    AverageGrade       = 2,
                    Description        = "Ok",
                    Address            = "Greek street 2037"
                },

                // hamar
                new Accomodation()
                {
                    Name = "Iceland Air",
                    AccomodationTypeId = accTypes[0].Id,
                    PlaceId            = places[7].Id,
                    OwnerId            = owner.appUserId,
                    Latitude           = 60.79453,
                    Longitude          = 11.06800,
                    AverageGrade       = 3.9,
                    Description        = "Recomended",
                    Address            = "310 Borgarnes"
                },
                new Accomodation()
                {
                    Name = "Scandic Hamar",
                    AccomodationTypeId = accTypes[0].Id,
                    PlaceId            = places[7].Id,
                    OwnerId            = owner.appUserId,
                    Latitude           = 60.79453,
                    Longitude          = 10.9,
                    AverageGrade       = 2.4,
                    Description        = "Welcome",
                    Address            = "Vangsvegen 121"
                },

                // havana
                new Accomodation()
                {
                    Name = "Inglaterra Hotel",
                    AccomodationTypeId = accTypes[0].Id,
                    PlaceId            = places[9].Id,
                    OwnerId            = owner.appUserId,
                    Latitude           = 23.11359,
                    Longitude          = -82.36660,
                    AverageGrade       = 4.4,
                    Description        = "Welcome to Havana",
                    Address            = " 416 Paseo de Marti"
                },
            };

            // ne moze na istom mestu dva smestaja da se isto zovu
            context.Accomodations.AddOrUpdate(acom => new { acom.Name, acom.PlaceId }, accoms.ToArray());
            ContextHelper.SaveChanges(context);
            #endregion

            //treba da dodamo ovo dodavanje soba i rezervacija
            #region AddingRooms

            var rooms = new List <Room>()
            {
                new Room()
                {
                    RoomNumber     = 1,
                    Description    = "ok",
                    BedCount       = 2,
                    AccomodationId = 1,
                    PricePerNight  = 10
                },

                new Room()
                {
                    RoomNumber     = 2,
                    Description    = "ok",
                    BedCount       = 2,
                    AccomodationId = 1,
                    PricePerNight  = 12
                },

                new Room()
                {
                    RoomNumber     = 3,
                    Description    = "ok",
                    BedCount       = 1,
                    AccomodationId = 1,
                    PricePerNight  = 15
                },

                new Room()
                {
                    RoomNumber     = 1,
                    Description    = "ok",
                    BedCount       = 3,
                    AccomodationId = 2,
                    PricePerNight  = 14
                },

                new Room()
                {
                    RoomNumber     = 2,
                    Description    = "ok",
                    BedCount       = 4,
                    AccomodationId = 2,
                    PricePerNight  = 20
                },

                new Room()
                {
                    RoomNumber     = 3,
                    Description    = "ok",
                    BedCount       = 2,
                    AccomodationId = 2,
                    PricePerNight  = 20
                }
            };

            // ne moze u istom hotelu dve sobe da imaju isti broj
            context.Rooms.AddOrUpdate(room => new { room.RoomNumber, room.AccomodationId }, rooms.ToArray());
            ContextHelper.SaveChanges(context);
            //ne znam sta treba da kucam kod ovog addOrUpdate

            #endregion

            #region AddingRoomReservations and comments
            #endregion
        }
Esempio n. 29
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!context.Users.Any(u => u.UserName == model.Username))
            {
                AppUser appUser = new AppUser();
                appUser.LastName         = model.LastName;
                appUser.Name             = model.Name;
                appUser.RoomReservations = new List <RoomReservation>();
                appUser.Comments         = new List <Comment>();
                appUser.Accommodations   = new List <Accommodation>();
                appUser.IsBanned         = false;

                context.AppUsers.Add(appUser);
                context.SaveChanges();
                var userr = context.AppUsers.Where(u => u.Name == model.Name && u.LastName == model.LastName).FirstOrDefault();

                var user = new BAIdentityUser()
                {
                    Id = model.Username, UserName = model.Username, Email = model.Email, AppUserId = userr.Id, AppUser = appUser, PasswordHash = BAIdentityUser.HashPassword(model.Password)
                };



                IdentityResult result = UserManager.Create(user);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }

                UserManager.AddToRole(user.Id, model.Role);

                return(Ok());
            }

            return(BadRequest());

            /*
             * if (!ModelState.IsValid)
             * {
             * return BadRequest(ModelState);
             * }
             *
             * AppUser appUser = new AppUser() { Name = model.Name, LastName = model.LastName };
             *
             * var user = new BAIdentityUser() { Id = model.Username, UserName = model.Username, Email = model.Email, AppUser = appUser, PasswordHash = BAIdentityUser.HashPassword(model.Password) };
             * UserManager.Create(user);
             */

            // var user = new BAIdentityUser() { UserName = model.Email, Email = model.Email };

            /*IdentityResult result = await UserManager.CreateAsync(user, model.Password);
             *
             *
             * if (!result.Succeeded)
             * {
             * // return GetErrorResult(result);
             * return BadRequest("Username is already taken by another user.");
             * }*/

            //   UserManager.AddToRole(user.Id, model.Role);

            //   return Ok();
        }
Esempio n. 30
0
        private void setDatabase()
        {
            var user = new BAIdentityUser();

            user.UserName     = "******";
            user.PasswordHash = BAIdentityUser.HashPassword("admin");
            user.Email        = "*****@*****.**";


            var user2 = new BAIdentityUser();

            user2.UserName     = "******";
            user2.PasswordHash = BAIdentityUser.HashPassword("appU");
            user2.Email        = "*****@*****.**";


            var accomod  = new Accommodation();
            var accomod2 = new Accommodation();
            var accomods = new List <Accommodation>()
            {
                accomod, accomod2
            };

            var accomType = new AccommodationType();

            accomType.Name = "Motel";
            //    accomType.Accommodations = accomods;

            var accomType2 = new AccommodationType();

            accomType2.Name = "Hotel";
            //  accomType2.Accommodations = accomods;


            var place  = new Place();
            var place2 = new Place();

            var room  = new Room();
            var room2 = new Room();
            var rooms = new List <Room>()
            {
                room, room2
            };

            var country = new Country();

            country.Name = "Serbia";

            country.Code = 43;


            var country2 = new Country();

            country2.Name = "Serbia";
            country2.Code = 44;



            var region = new Region();

            region.Name    = "Zlatibor";
            region.Country = country;
            region.Places  = new List <Place>()
            {
                place, place2
            };


            var region2 = new Region();

            region2.Name    = "Jahorina";
            region2.Country = country2;
            region2.Places  = new List <Place>()
            {
                place, place2
            };
            country2.Regions = new List <Region>()
            {
                region2
            };
            country.Regions = new List <Region>()
            {
                region, region2
            };

            place.Name     = "place1";
            place.RegionId = 1;
            //  place.Accommodations = new List<Accommodation>() { accomod, accomod2 };

            place2.Name     = "place2";
            place2.RegionId = 1;

            accomod.Id       = 1;
            accomod.Address  = "Jovana Subotica";
            accomod.Name     = "accomod1";
            accomod.Approved = true;
            accomod.User     = user;

            accomod.AvrageGrade      = 50;
            accomod.Description      = "opisAccom";
            accomod.AccomodationType = accomType;
            accomod.ImageURL         = "https://images.pexels.com/photos/164595/pexels-photo-164595.jpeg?auto=compress&cs=tinysrgb&h=350";
            accomod.Latitude         = 49;
            accomod.Longitude        = 19;
            accomod.Place            = place;
            accomod.Rooms            = rooms;

            accomod2.Id       = 2;
            accomod2.Address  = "Nikole Pasica";
            accomod2.Name     = "accomod2";
            accomod2.Approved = true;
            accomod2.User     = user2;

            accomod2.AvrageGrade      = 40;
            accomod2.Description      = "opisAccom2";
            accomod2.AccomodationType = accomType2;
            accomod2.ImageURL         = "https://www.rd.com/wp-content/uploads/2017/11/Here%E2%80%99s-What-You-Can-and-Can%E2%80%99t-Steal-from-Your-Hotel-Room_363678794-Elnur-760x506.jpg";
            accomod2.Latitude         = 56.43;
            accomod2.Longitude        = 10.39;
            accomod2.Place            = place2;
            //  place.Accommodations = new List<Accommodation>() { accomod, accomod2 };
            //  place2.Accommodations = new List<Accommodation>() { accomod, accomod2 };

            var comment = new Comment()
            {
                User = user, Text = "dobar", Grade = 10, Accomodation = accomod
            };
            var comment2 = new Comment()
            {
                User = user2, Text = "los", Grade = 2, Accomodation = accomod2
            };

            accomod.Comments = new List <Comment> {
                comment
            };
            accomod2.Comments = new List <Comment> {
                comment
            };
            room.Description   = "opisSobe1";
            room.PricePerNight = 100;
            room.RoomNumber    = 4;
            room.BedCount      = 3;
            room.Accomodation  = accomod;


            room2.Description   = "opisSobe12";
            room2.PricePerNight = 97;
            room2.RoomNumber    = 6;
            room2.BedCount      = 3;
            room2.Accomodation  = accomod2;

            accomod.Rooms = rooms;

            var roomReservations  = new RoomReservations();
            var roomReservations2 = new RoomReservations();

            roomReservations.Room      = room;
            roomReservations.User      = user;
            roomReservations.Timestamp = "5";
            roomReservations.StartDate = "Danas";
            roomReservations.EndDate   = "Sutra";

            roomReservations2.Room      = room2;
            roomReservations2.User      = user2;
            roomReservations2.Timestamp = "8";
            roomReservations2.StartDate = "Danas";
            roomReservations2.EndDate   = "Prekosutra";

            room.RoomReservations = new List <RoomReservations> {
                roomReservations
            };
            room2.RoomReservations = new List <RoomReservations> {
                roomReservations2
            };

            HelperJebeni.accomodations = new List <Accommodation>();
            HelperJebeni.accomodations.Add(accomod);
            HelperJebeni.accomodations.Add(accomod2);
        }