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

            var appUser = new AppUser();

            appUser.Username = model.Username;
            appUser.Role     = model.Role;
            appUser.Birthday = model.Birthday;
            db.AppUsers.Add(appUser);
            db.SaveChanges();

            var user = new RAIdentityUser(appUser.Id, model.Username, model.Email);

            user.PasswordHash = RAIdentityUser.HashPassword(model.Password);

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

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

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


            return(Ok());
        }
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Please fill out all fields and enter correct values."));
            }

            var appUser = new AppUser()
            {
                FullName = model.FullName, Email = model.Email, Birthday = model.Birthday, Activated = false, PersonalDocument = model.PersonalDocument
            };
            var user = new RAIdentityUser()
            {
                UserName = model.Email, Email = model.Email, AppUser = appUser
            };

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

            UserManager.AddToRole(user.Id, "AppUser");

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

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

            AppUser appUser = new AppUser()
            {
                FullName    = model.FullName,
                DateOfBirth = DateTime.Parse(model.DateOfBirth)
            };

            var user = new RAIdentityUser()
            {
                UserName = model.Email, Email = model.Email, AppUser = appUser, PasswordHash = RAIdentityUser.HashPassword(model.Password)
            };


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

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

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

            return(Ok());
        }
        public IHttpActionResult Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new RAIdentityUser()
            {
                Id       = model.Email,
                UserName = model.Email,
                Email    = model.Email,
                AppUser  = new AppUser
                {
                    FullName  = model.FirstName + " " + model.LastName,
                    Email     = model.Email,
                    BirthDate = DateTime.Parse(model.BirthDate),
                    ManagerCreationAllowed = false,
                    Approved = false,
                }
            };

            IdentityResult createUser = UserManager.Create(user, model.Password);

            if (createUser.Succeeded)
            {
                IdentityResult roleResult = UserManager.AddToRole(user.Id, "AppUser");
                if (roleResult.Succeeded)
                {
                    return(Ok());
                }
            }

            return(BadRequest());
        }
Exemplo n.º 5
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            AppUser appUser = new AppUser();

            appUser.Email     = model.Email;
            appUser.Activated = false;
            appUser.FullName  = model.FullName;
            appUser.Birthday  = DateTime.Parse(model.Date);
            appUser.Rents     = new List <Rent>();

            var user = new RAIdentityUser()
            {
                UserName = model.Email, Email = model.Email, AppUser = appUser, PasswordHash = RAIdentityUser.HashPassword(model.Password)
            };

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

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

            UserManager.AddToRole(user.Id, "AppUser"); // Dajemo rolu

            return(Ok());
        }
Exemplo n.º 6
0
        public IHttpActionResult PostBranch(Branch branch)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string         username = User.Identity.Name;
            RAIdentityUser RAUser   = db.Users.GetAll().First(u => u.UserName == username);
            AppUser        appUser  = db.AppUsers.Get(RAUser.AppUserId);

            if (appUser.IsManagerAllowed == false)
            {
                return(BadRequest("You are not allowed."));
            }

            Service service = db.Services.Get(branch.BranchServiceId);

            if (service.ServiceManagerId != appUser.Id)
            {
                return(BadRequest("You are not authorized, not manager of this service."));
            }

            if (!service.IsConfirmed)
            {
                return(BadRequest("Service is not confirmed yet."));
            }

            db.Branches.Add(branch);
            db.Complete();

            return(CreatedAtRoute("DefaultApi", new { id = branch.Id }, branch));
        }
Exemplo n.º 7
0
        public IHttpActionResult DeletePricelist(int id)
        {
            Pricelist item = db.Pricelists.Get(id);

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

            string         username = User.Identity.Name;
            RAIdentityUser RAUser   = db.Users.GetAll().First(u => u.UserName == username);
            AppUser        appUser  = db.AppUsers.Get(RAUser.AppUserId);

            Service service = db.Services.Get(item.PricelistServiceId);

            if (service.ServiceManagerId != appUser.Id)
            {
                return(BadRequest("You are not authorized."));
            }

            if (appUser.IsManagerAllowed == false)
            {
                return(BadRequest("You are not allowed."));
            }


            db.Pricelists.Remove(item);
            db.Complete();

            return(Ok(item));
        }
Exemplo n.º 8
0
        public IHttpActionResult PostPricelist(Pricelist pricelist)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string         username = User.Identity.Name;
            RAIdentityUser RAUser   = db.Users.GetAll().First(u => u.UserName == username);
            AppUser        appUser  = db.AppUsers.Get(RAUser.AppUserId);

            if (appUser.IsManagerAllowed == false)
            {
                return(BadRequest("You are not allowed."));
            }

            List <Item> items = pricelist.Items;

            pricelist.Items = null;
            db.Pricelists.Add(pricelist);
            db.Complete();

            foreach (Item item in items)
            {
                item.ItemPriceListId = pricelist.Id;
                db.Items.Add(item);
            }
            db.Complete();
            return(CreatedAtRoute("DefaultApi", new { id = pricelist.Id }, pricelist));
        }
Exemplo n.º 9
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>();

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

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

            RADBContext db = new RADBContext();



            string fullName = db.AppUsers.SingleOrDefault(r => r.UserId == user.AppUserId).FullName;


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

            oAuthIdentity.AddClaim(new Claim("UserFullName", fullName));
            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            context.Validated(ticket);
        }
Exemplo n.º 10
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new RAIdentityUser()
            {
                UserName = model.Email, Email = model.Email, AppUser = new AppUser {
                    Birthday = model.Birthday, Email = model.Email, FullName = model.FullName
                }
            };
            AppUser userDB = unitOfWork.AppUsers.GetUser(user.Email);

            if (userDB == null)
            {
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

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

                UserManager.AddToRole(user.Id, "AppUser");

                return(Ok());
            }
            else
            {
                return(Unauthorized());
            }
        }
Exemplo n.º 11
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            NotificationsHub.NotifyAdmin("New user is added...");
            var appUser = new AppUser()
            {
                FullName = model.FullName, Email = model.Email, BirthDay = model.DateOfBirth,                          /*CreatingServicesBan = true,*/ /*IsRegistered = false*/
            };

            var user = new RAIdentityUser()
            {
                Id = model.Email, UserName = model.Email, Email = model.Email, AppUser = appUser
            };

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

            await UserManager.AddToRoleAsync(model.Email, "AppUser");

            if (!result.Succeeded)
            {
                return(Content(System.Net.HttpStatusCode.BadRequest, "User already exists!"));
            }
            return(Ok());
        }
Exemplo n.º 12
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 RAIdentityUser()
            {
                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());
        }
Exemplo n.º 13
0
        public IHttpActionResult ToggleVehicleAvailability(int vehicleId)
        {
            Vehicle vehicle = db.Vehicles.Get(vehicleId);

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

            string         username = User.Identity.Name;
            RAIdentityUser RAUser   = db.Users.Get(username);
            AppUser        appUser  = db.AppUsers.Get(RAUser.AppUserId);

            Service service = db.Services.Get(vehicle.VehicleServiceId);

            if (service.ServiceManagerId != appUser.Id)
            {
                return(BadRequest("You are not authorized."));
            }

            if (appUser.IsManagerAllowed == false)
            {
                return(BadRequest("You are not allowed."));
            }

            vehicle.IsAvailable = !vehicle.IsAvailable;
            db.Vehicles.Update(vehicle);
            db.Complete();

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

            var appUser = new AppUser()
            {
                Email = model.Email, FullName = model.Name + " " + model.LastName, Birthday = model.Birthday
            };
            var user = new RAIdentityUser()
            {
                Id = model.Email, UserName = model.Email, Email = model.Email, AppUser = appUser, PasswordHash = RAIdentityUser.HashPassword(model.Password)
            };

            UserManager.Create(user);
            if (model.Role)
            {
                UserManager.AddToRole(user.Id, "Manager");
            }
            else
            {
                UserManager.AddToRole(user.Id, "AppUser");
            }

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

            AppUser appUser = new AppUser()
            {
                FullName = model.FullName, Email = model.Email, BirthDate = model.BirthDate
            };
            var user = new RAIdentityUser()
            {
                UserName = model.Email, Email = model.Email, AppUser = appUser, PasswordHash = RAIdentityUser.HashPassword(model.Password)
            };

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


            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }
            UserManager.AddToRole(user.Id, "AppUser");
            NotificationsHub.NotifyAdmin("New User was registered");
            return(Ok());
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            //RAIdentityUser user = userManager.Find(context.UserName, context.Password);
            RAIdentityUser 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);
        }
Exemplo n.º 17
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>();

            RAIdentityUser 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);
        }
Exemplo n.º 18
0
        public async Task <IHttpActionResult> ApproveService([FromBody] long id)
        {
            if (unitOfWork.Services.Get(id) == null)
            {
                return(BadRequest("Bad request. Id don't exists."));
            }

            Service serviceForApprove = unitOfWork.Services.Get(id);

            RAIdentityUser user = await UserManager.FindByIdAsync(serviceForApprove.Creator);

            serviceForApprove.IsApproved = true;

            SMTPService.SendMail("Service approved", "Your service " + serviceForApprove.Name + " is approved, now you can add branch offices and vehicles.", user.Email);

            try
            {
                lock (lockObjectForServices)
                {
                    unitOfWork.Services.Update(serviceForApprove);
                    unitOfWork.Complete();
                }
            }
            catch (DBConcurrencyException)
            {
                return(NotFound());
            }

            return(Ok("Service Successfully approved."));
        }
Exemplo n.º 19
0
        public async Task <IHttpActionResult> RejectService([FromBody] long id)
        {
            if (unitOfWork.Services.Get(id) == null)
            {
                return(BadRequest("Bad request. Id don't exists."));
            }

            Service serviceForApprove = unitOfWork.Services.Get(id);

            RAIdentityUser user = await UserManager.FindByIdAsync(serviceForApprove.Creator);

            SMTPService.SendMail("Service rejected", "Your service " + serviceForApprove.Name + " is rejected.", user.Email);

            ImageHelper.DeleteImage(serviceForApprove.LogoImage);

            try
            {
                lock (lockObjectForServices)
                {
                    unitOfWork.Services.Remove(serviceForApprove);
                    unitOfWork.Complete();
                }
            }
            catch (DBConcurrencyException)
            {
                return(NotFound());
            }

            return(Ok("Service Successfully rejected."));
        }
Exemplo n.º 20
0
        public async Task <IHttpActionResult> HasUserRated([FromUri] long serviceId)
        {
            bool hasUserRated = false;

            Service service = unitOfWork.Services.Get(serviceId);

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

            RAIdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            if (user == null)
            {
                return(Ok(true));
            }

            Rating rating = service.Ratings.Find(rate => rate.UserId == user.Id);

            if (rating == null)
            {
                hasUserRated = false;
            }
            else
            {
                hasUserRated = true;
            }

            return(Ok(hasUserRated));
        }
Exemplo n.º 21
0
        public IHttpActionResult GetRatings([FromUri] long serviceId)
        {
            Service service = unitOfWork.Services.Get(serviceId);

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

            List <Rating> ratings = new List <Rating>();

            RAIdentityUser user = null;

            foreach (Rating rating in service.Ratings)
            {
                user = UserManager.FindById(rating.UserId);
                ratings.Add(new Rating()
                {
                    Id     = rating.Id,
                    UserId = user.Email,
                    Value  = rating.Value
                });
            }

            return(Ok(ratings));
        }
Exemplo n.º 22
0
        public IHttpActionResult GetComments([FromUri] long serviceId)
        {
            Service service = unitOfWork.Services.Get(serviceId);

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

            RAIdentityUser user     = null;
            List <Comment> comments = new List <Comment>();

            foreach (Comment comment in service.Comments)
            {
                user = UserManager.FindById(comment.UserId);
                comments.Add(new Comment()
                {
                    Id       = comment.Id,
                    UserId   = user.Email,
                    Text     = comment.Text,
                    DateTime = comment.DateTime
                });
            }

            return(Ok(comments));
        }
Exemplo n.º 23
0
        public IHttpActionResult Register(RegisterBindingModel model)
        {
            AppUser appUser = new AppUser()
            {
                Name      = model.Name,
                Surname   = model.Surname,
                Approved  = false,
                ImagePath = ""
            };



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

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

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

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

            return(Ok());
        }
Exemplo n.º 24
0
        //[Authorize(Roles = "AppUser")]
        public IHttpActionResult Reservation()
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            ReservationModel reservationModel = new ReservationModel();
            PriceList        priceList        = new PriceList();
            var            httpRequest        = HttpContext.Current.Request;
            RAIdentityUser user = null;

            try
            {
                reservationModel = JsonConvert.DeserializeObject <ReservationModel>(httpRequest.Form[0]);

                user = db.Users
                       .Where(b => b.UserName == reservationModel.UserName)
                       .FirstOrDefault();

                foreach (AppUser u in db.AppUsers)
                {
                    if (u.Id == user.AppUserId)
                    {
                        priceList.UserId = u.Id;
                        priceList.User   = u;
                    }
                }

                priceList.TimeOfReservation = reservationModel.TimeOfReservation;
                priceList.TimeToReturn      = reservationModel.TimeToReturn;
                priceList.TakeOfficeId      = reservationModel.TakeOfficeId;
                priceList.ReturnOfficeId    = reservationModel.ReturnOfficeId;
                priceList.TakeOffice        = db.Offices.Find(reservationModel.TakeOfficeId);
                priceList.ReturnOffice      = db.Offices.Find(reservationModel.ReturnOfficeId);
            }
            catch (JsonSerializationException)
            {
                return(BadRequest(ModelState));
            }

            db.PriceLists.Add(priceList);

            try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException)
            {
                return(BadRequest(ModelState));
            }
            catch (DbUpdateException)
            {
                return(BadRequest(ModelState));
            }


            return(Ok(priceList.Id));
        }
        public async Task <IHttpActionResult> PostBranchOffice(CreateBranchOfficeBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            HttpRequest httpRequest = HttpContext.Current.Request;

            if (!ImageHelper.ValidateImage(httpRequest.Files[0], out validationErrorMessage))
            {
                return(BadRequest(validationErrorMessage));
            }

            RAIdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            Service service = unitOfWork.Services.Get(model.ServiceId);

            if (service == null)
            {
                return(BadRequest("Service don't exists."));
            }

            if (UserManager.IsInRole(user.Id, "Manager") && !UserManager.IsInRole(user.Id, "Admin"))
            {
                if (service.Creator != user.Id)
                {
                    return(BadRequest("Access denied."));
                }
            }

            BranchOffice branchOffice = new BranchOffice
            {
                Address   = model.Address,
                Latitude  = model.Latitude,
                Longitude = model.Longitude,
                Image     = ImageHelper.SaveImageToServer(httpRequest.Files[0])
            };

            try
            {
                lock (lockObjectForBranchOffices)
                {
                    service.BranchOfficces.Add(branchOffice);

                    unitOfWork.Services.Update(service);

                    unitOfWork.BranchOffices.Add(branchOffice);
                    unitOfWork.Complete();
                }
            }
            catch (DBConcurrencyException)
            {
                return(NotFound());
            }

            return(Ok("Branch office successfully created"));
        }
Exemplo n.º 26
0
        public IHttpActionResult PostVehicle(VehicleDTO vehicleDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string         username = User.Identity.Name;
            RAIdentityUser RAUser   = db.Users.Get(username);
            AppUser        appUser  = db.AppUsers.Get(RAUser.AppUserId);

            if (appUser.IsManagerAllowed == false)
            {
                return(BadRequest("You are not allowed."));
            }

            Vehicle vehicle = new Vehicle();

            vehicle.Description      = vehicleDTO.Description;
            vehicle.Id               = vehicleDTO.Id;
            vehicle.IsAvailable      = vehicleDTO.IsAvailable;
            vehicle.Manufacturer     = vehicleDTO.Manufacturer;
            vehicle.Model            = vehicleDTO.Model;
            vehicle.TypeId           = vehicleDTO.TypeId;
            vehicle.VehicleServiceId = vehicleDTO.VehicleServiceId;
            vehicle.YearOfProduction = vehicleDTO.YearOfProduction;

            Service service = db.Services.GetWithPricelists(vehicle.VehicleServiceId);

            if (!service.IsConfirmed)
            {
                return(BadRequest("Service is not confirmed yet."));
            }

            Item item = new Item();

            item.ItemVehicleId = vehicle.Id;

            Pricelist actualPricelist = service.Pricelists[0];

            foreach (Pricelist pricelist in service.Pricelists.Where(p => p.BeginTime <= DateTime.Now.Date))
            {
                if (pricelist.EndTime > actualPricelist.EndTime)
                {
                    actualPricelist = pricelist;
                }
            }
            item.ItemPriceListId = actualPricelist.Id;
            item.Price           = vehicleDTO.PricePerHour;
            db.Vehicles.Add(vehicle);
            db.Items.Add(item);
            db.Complete();

            return(CreatedAtRoute("DefaultApi", new { id = vehicle.Id }, vehicle));
        }
Exemplo n.º 27
0
        public IHttpActionResult PutService(int id, Service service)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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

            string         username = User.Identity.Name;
            RAIdentityUser RAUser   = db.Users.Get(username);
            AppUser        appUser  = db.AppUsers.Get(RAUser.AppUserId);


            if (service.ServiceManagerId != appUser.Id)
            {
                return(BadRequest("You are not authorized."));
            }


            if (appUser.IsManagerAllowed == false)
            {
                return(BadRequest("You are not allowed."));
            }

            Service serv = db.Services.Get(service.Id);

            serv.Name        = service.Name;
            serv.Email       = service.Email;
            serv.Description = service.Description;

            db.Services.Update(serv);

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

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemplo n.º 28
0
        public IHttpActionResult PutBranch(int id, Branch branch)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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


            string         username = User.Identity.Name;
            RAIdentityUser RAUser   = db.Users.GetAll().First(u => u.UserName == username);
            AppUser        appUser  = db.AppUsers.Get(RAUser.AppUserId);

            Service service = db.Services.Get(branch.BranchServiceId);

            if (service.ServiceManagerId != appUser.Id)
            {
                return(BadRequest("You are not authorized."));
            }

            if (!service.IsConfirmed)
            {
                return(BadRequest("Service is not confirmed yet."));
            }

            if (appUser.IsManagerAllowed == false)
            {
                return(BadRequest("You are not allowed."));
            }

            db.Branches.Update(branch);

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

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemplo n.º 29
0
        public IHttpActionResult PostComment(Comment item)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string         username = User.Identity.Name;
            RAIdentityUser RAUser   = db.Users.Get(username);

            if (RAUser == null)
            {
                return(BadRequest());
            }
            AppUser appUser = db.AppUsers.Get(RAUser.AppUserId);

            if (appUser.Id != item.UserId)
            {
                return(BadRequest());
            }

            List <Comment> comments = db.Comments.GetCommentsOfUser(item.UserId).ToList();
            Comment        comment  = comments.FirstOrDefault(c => c.CommentedServiceId == item.CommentedServiceId);

            if (comment != null)
            {
                return(BadRequest("You can comment only once."));
            }

            List <Reservation> reservations = db.Reservations.GetAllReservationsOfUserWithBranchesAndService(appUser.Id).ToList();
            bool firstFinishedReservation   = false;

            foreach (Reservation reservation in reservations)
            {
                if (reservation.BranchTake.BranchService.Id == item.CommentedServiceId)
                {
                    if (reservation.EndTime < DateTime.Now.Date)
                    {
                        firstFinishedReservation = true;
                        break;
                    }
                }
            }
            if (!firstFinishedReservation)
            {
                return(BadRequest("You can comment only after first finished reservation in this service."));
            }
            db.Comments.Add(item);
            db.Complete();

            return(CreatedAtRoute("DefaultApi", new { id = item.Id }, item));
        }
Exemplo n.º 30
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));
            }

            RAIdentityUser 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());
        }