Beispiel #1
0
 // PUT api/<controller>/5
 public HttpResponseMessage Put(int id, [FromBody] Person person)
 {
     if (Request.Headers.Contains("Authorization"))
     {
         string type = Request.Headers.GetValues("Authorization").FirstOrDefault()?.Split(' ').First();
         if (type == "Bearer")
         {
             var token = Request.Headers.GetValues("Authorization").FirstOrDefault()?.Split(' ').Last();
             if (AuthJWT.ValidateJwtToken(token))
             {
                 return(PutPerson(id, person));
             }
             return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid token"));
         }
         if (type == "Basic")
         {
             var authHeader      = Request.Headers.GetValues("Authorization").FirstOrDefault()?.Split(' ').Last();
             var credentialBytes = Convert.FromBase64String(authHeader);
             var credentials     = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
             var user            = users.SingleOrDefault(x => x.Username == credentials[0] && x.Password == credentials[1]);
             if (user != null)
             {
                 return(PutPerson(id, person));
             }
             return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Username or password is incorrect"));
         }
     }
     return(Request.CreateResponse(HttpStatusCode.Unauthorized, "No authorization header"));
 }
        public async Task GetActualProject(string town, int lastId = 0)//<List<ProjectShort>>
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int status);

            if (status != 0 || userId == null)
            {
                userId = null;
            }
            //List<ProjectShort> res = new List<ProjectShort>();

            int?townId = null;

            if (town != null)
            {
                string townLower = town.ToLower().Trim();
                var    townDb    = await Town.GetByName(_db, townLower);

                if (townDb == null)
                {
                    return;// new List<ProjectShort>();
                }
                townId = townDb.Id;
            }
            var res = await Project.GetActualShortEntityWithStatus(_db, townId, userId, lastId);

            await ProjectShort.SetMainImages(_db, res);

            //return res;
            Response.ContentType = "application/json";
            await Response.WriteAsync(JsonConvert.SerializeObject(res, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
Beispiel #3
0
 public HttpResponseMessage Get(string name    = null, string surname = null, string city = null, int?year = null,
                                bool lowercase = false, bool contains = false)
 {
     if (Request.Headers.Contains("Authorization"))
     {
         string type = Request.Headers.GetValues("Authorization").FirstOrDefault()?.Split(' ').First();
         if (type == "Bearer")
         {
             var token = Request.Headers.GetValues("Authorization").FirstOrDefault()?.Split(' ').Last();
             if (AuthJWT.ValidateJwtToken(token))
             {
                 return(FindPerson(name, surname, city, year, lowercase, contains));
             }
             return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid token"));
         }
         if (type == "Basic")
         {
             var authHeader      = Request.Headers.GetValues("Authorization").FirstOrDefault()?.Split(' ').Last();
             var credentialBytes = Convert.FromBase64String(authHeader);
             var credentials     = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
             var user            = users.SingleOrDefault(x => x.Username == credentials[0] && x.Password == credentials[1]);
             if (user != null)
             {
                 return(FindPerson(name, surname, city, year, lowercase, contains));
             }
             return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Username or password is incorrect"));
         }
     }
     return(Request.CreateResponse(HttpStatusCode.Unauthorized, "No authorization header"));
 }
Beispiel #4
0
        public async Task <bool?> DeleteUserFromCompany([FromForm] int companyId, [FromForm] string newUserId, StatusInCompany status)
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int statusId);

            if (statusId != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return(null);
            }
            var company = await Company.GetIfAccess(_db, userId, companyId);

            if (company == null)
            {
                Response.StatusCode = 404;
                return(null);
            }
            var res = await company.RemoveUser(_db, newUserId, status);// StatusInCompany.Moderator);

            if (res == null)
            {
                Response.StatusCode = 527;
                return(null);
            }
            return(res);
        }
Beispiel #5
0
        public async Task RefreshToken([FromForm] string refreshToken)//, string confirmPassword
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int status);

            if ((status != 0 && status != 1) || userId == null)
            {
                Response.StatusCode = 401;
                return;
            }

            var tokens = await AuthJWT.Refresh(_db, userId, refreshToken);

            if (tokens == null)
            {
                Response.StatusCode = 401;
                return;
            }
            var response = new
            {
                access_token  = tokens.Item1,
                refresh_token = tokens.Item2
            };

            Response.ContentType = "application/json";
            await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));


            //return status.ToString();
        }
Beispiel #6
0
        public async Task GetStudents(int projectId, StatusInProject status)
        {
            if (status != StatusInProject.Approved && status != StatusInProject.Canceled && status != StatusInProject.InProccessing)
            {
                Response.StatusCode = 400;
                return;// null;
            }

            string userId = AuthJWT.GetCurrentId(HttpContext, out int statusId);

            if (statusId != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return;// null;
            }

            var proj = await ApplicationUser.CheckAccessEditProject(_db, projectId, userId);

            if (proj == null)
            {
                Response.StatusCode = 404;
                return;// null;
            }

            var usersShort = await proj.GetStudentsShortEntity(_db, status);

            Response.ContentType = "application/json";
            await Response.WriteAsync(JsonConvert.SerializeObject(usersShort, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));

            //return usersShort;
        }
Beispiel #7
0
        public async Task <bool> ChangeStatusUserProject([FromForm] int projectId, [FromForm] string studentId, [FromForm] StatusInProject newStatus)
        {
            if (newStatus != StatusInProject.InProccessing && newStatus != StatusInProject.Canceled && newStatus != StatusInProject.Approved && newStatus != StatusInProject.Moderator)
            {
                Response.StatusCode = 400;
                return(false);
            }
            string userId = AuthJWT.GetCurrentId(HttpContext, out int statusId);

            if (statusId != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return(false);
            }

            var proj = await ApplicationUser.CheckAccessEditProject(_db, projectId, userId);

            if (proj == null)
            {
                Response.StatusCode = 404;
                return(false);
            }
            bool?res = await proj.ChangeStatusUserByLead(_db, newStatus, studentId);

            if (res == null)
            {
                Response.StatusCode = 527;
                return(false);// null;
            }

            return((bool)res);
        }
Beispiel #8
0
        public async Task <bool> ChangeStatusProject([FromForm] int projectId, [FromForm] StatusProject newStatus)
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int statusId);

            if (statusId != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return(false);
            }

            var proj = await ApplicationUser.CheckAccessEditProject(_db, projectId, userId);

            if (proj == null)
            {
                Response.StatusCode = 404;
                return(false);
            }
            try
            {
                await proj.SetStatus(_db, newStatus);
            }
            catch (DbUpdateConcurrencyException)
            {
                Response.StatusCode = 527;
                return(false);
            }

            return(true);
        }
Beispiel #9
0
        public string LoginJWT(string register, string senha, int idAplicacao, int validadeEmMinutos = 0)
        {
            string token     = "";
            int    matricula = 0;

            if (_authDataRepository.Login(register, senha, idAplicacao) || new ClienteEntity().UserGolden(register, (Aplicacoes)idAplicacao) == 1)
            {
                token = AuthJWT.GeraJwt(matricula, validadeEmMinutos);
            }
            return(token);
        }
Beispiel #10
0
 public HttpResponseMessage Get()
 {
     if (Request.Headers.Contains("Authorization"))
     {
         var token = Request.Headers.GetValues("Authorization").FirstOrDefault()?.Split(' ').Last();
         if (AuthJWT.ValidateJwtToken(token))
         {
             return(Request.CreateResponse(HttpStatusCode.OK, users));
         }
         return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid token"));
     }
     return(Request.CreateResponse(HttpStatusCode.Unauthorized, "No authorization header"));
 }
        public async Task GetProjectByContainsName(string projectName, int?townId, int lastId = 0)
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int status);

            if (status != 0 || userId == null)
            {
                userId = null;
            }
            var res = await Project.GetByStartName(_db, townId, userId, projectName, lastId);

            Response.ContentType = "application/json";
            await Response.WriteAsync(JsonConvert.SerializeObject(res, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
Beispiel #12
0
        private AuthenticateResponse Authenticate(AuthenticateRequest authenticateRequest)
        {
            var user = users.SingleOrDefault(x => x.Username == authenticateRequest.Username && x.Password == authenticateRequest.Password);

            // return null if user not found
            if (user == null)
            {
                return(null);
            }

            // authentication successful so generate jwt token
            var token = AuthJWT.generateJwtToken(user);

            return(new AuthenticateResponse(user, token));
        }
        public async Task GetUserResponsibilityProjects()
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int status);

            if (status != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return;// null;
            }
            var res = await ApplicationUser.GetUserResponsibilityProjects(_db, userId);

            Response.ContentType = "application/json";
            await Response.WriteAsync(JsonConvert.SerializeObject(res, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
Beispiel #14
0
        public async Task <int?> CreateProject([FromForm] Project project, [FromForm] string[] competences = null,
                                               [FromForm] string[] townNames = null, [FromForm] IFormFile[] uploadedFile = null)
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int statusId);

            if (statusId != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return(null);
            }

            if (!ModelState.IsValid)
            {
                Response.StatusCode = 404;
                return(null);
            }

            if (townNames == null || townNames.Length == 0)
            {
                Response.StatusCode = 400;
                return(null);
            }

            if (!await ApplicationUser.CheckAccessEditCompany(_db, project.CompanyId, userId))
            {
                Response.StatusCode = 404;
                return(null);
            }


            Project newProject = new Project(project.Name, project.Description, project.Payment, project.CompanyId);

            newProject.Validation(new ValidationInput());
            _db.Projects.Add(newProject);
            await _db.SaveChangesAsync();

            await newProject.AddImagesToDbSystem(_db, _appEnvironment, uploadedFile);

            await newProject.AddCompetences(_db, competences);

            Town.Validation(new ValidationInput(), townNames);
            await Project.AddTowns(_db, newProject.Id, townNames.ToList());

            // await _db.SaveChangesAsync();

            return(newProject.Id);
        }
Beispiel #15
0
        public async Task <bool?> ChangeCompany([FromForm] Company company, [FromForm] IFormFile[] uploadedFile = null)
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int statusId);

            if (statusId != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return(null);
            }


            if (company.Id == 0)
            {
                ModelState.AddModelError("Id", "Не передан Id");
            }
            if (!ModelState.IsValid)
            {
                Response.StatusCode = 400;
                return(null);
            }

            var oldCompany = await Company.GetIfAccess(_db, userId, company.Id);

            //var oldCompany = await _db.Companys.FirstOrDefaultAsync(x1 => x1.Id == company.Id);
            if (oldCompany == null)
            {
                Response.StatusCode = 404;
                return(null);
            }
            //byte[] newImage = null;

            try
            {
                oldCompany.ChangeData(company.Name, company.Description, company.Number, company.Email);//, company.Image);
                oldCompany.Validation(new ValidationInput());
                await _db.SaveChangesAsync();

                await oldCompany.SetImage(_db, uploadedFile, _appEnvironment);
            }
            catch (DbUpdateConcurrencyException)
            {
                Response.StatusCode = 527;
                return(null);
            }

            return(true);//oldCompany
        }
        public async Task GetCompany(int id)
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int status);

            if (status != 0 || userId == null)
            {
                userId = null;
            }
            var company = await Company.Get(_db, id);//(int)

            CompanyPage res = await CompanyPage.LoadAllForView(_db, company, userId);

            Response.ContentType = "application/json";
            await Response.WriteAsync(JsonConvert.SerializeObject(res, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
        public async Task <bool?> ChangeUserData([FromForm] ApplicationUser newUser, [FromForm] string[] competences, [FromForm] int[] competenceIds)
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int statusId);

            if (statusId != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return(false);
            }
            newUser.Id = userId;
            newUser.Validation(new ValidationInput());
            var user = await ApplicationUser.ChangeData(_db, _userManager, newUser);

            await user.AddCompetences(_db, competences);

            await user.DeleteCompetences(_db, competenceIds);

            return(true);
        }
        public async Task <bool?> ChangeStatusStudentInProject([FromForm] int projectId, [FromForm] Models.StatusInProject newStatus)
        {
            if (newStatus != StatusInProject.InProccessing && newStatus != StatusInProject.CanceledByStudent)
            {
                Response.StatusCode = 400;
                return(null);
            }
            string userId = AuthJWT.GetCurrentId(HttpContext, out int status);

            if (status != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return(null);
            }

            //---------------этот кусок нужен
            //var user = await ApplicationUser.Get(_userManager, userId);
            //bool mailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
            //if (!mailConfirmed)
            //{
            //    Response.StatusCode = 406;
            //    return null;
            //}


            var project = await Project.Get(_db, projectId);

            if (project == null)
            {
                Response.StatusCode = 404;
                return(null);
            }
            bool?res = await project.CreateChangeStatusUser(_db, newStatus, userId);

            if (res == null)
            {
                Response.StatusCode = 527;
                return(null);// null;
            }

            return(res);
        }
        public async Task <bool?> ChangeStatusUserInCompany([FromForm] int companyId, [FromForm] Models.StatusInCompany newStatus)
        {
            if (newStatus != StatusInCompany.RequestedByUser && newStatus != StatusInCompany.Empty)
            {
                Response.StatusCode = 400;
                return(null);
            }
            string userId = AuthJWT.GetCurrentId(HttpContext, out int status);

            if (status != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return(null);
            }

            //---------------этот кусок нужен
            //var user = await ApplicationUser.Get(_userManager, userId);
            //bool mailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
            //if (!mailConfirmed)
            //{
            //    Response.StatusCode = 406;
            //    return null;
            //}


            var company = await Company.Get(_db, companyId);

            if (company == null)
            {
                Response.StatusCode = 404;
                return(null);
            }
            bool?res = await company.CreateChangeStatusUser(_db, newStatus, userId);

            if (res == null)
            {
                Response.StatusCode = 527;
                return(null);// null;
            }

            return(res);
        }
Beispiel #20
0
        public async Task Login([FromForm] string username, [FromForm] string password)
        {
            //try
            //{


            var user = await ApplicationUser.LoginGet(_userManager, username, password);

            //}
            //catch(Exception e)
            //{
            //    var asd = 1;
            //}
            if (user == null)
            {
                Response.StatusCode = 400;
                await Response.WriteAsync("Invalid username or password.");

                return;
            }
            var identity = AuthJWT.GetIdentity(user);

            var encodedJwt    = AuthJWT.GenerateMainToken(identity);
            var encodedRefJwt = AuthJWT.GenerateRefreshToken();
            await user.SetRefreshToken(_db, encodedRefJwt);

            var response = new
            {
                access_token  = encodedJwt,
                refresh_token = encodedRefJwt,
                username      = identity.Name
            };

            // сериализация ответа
            Response.ContentType = "application/json";
            await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
        public async Task GetProject(int?id)
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int status);

            if (status != 0 || userId == null)
            {
                userId = null;
            }
            var proj = await Project.Get(_db, id);

            if (proj == null)
            {
                Response.StatusCode = 404;
                return;// null;
            }
            var res = await ProjectPage.LoadAllForView(_db, proj, userId);


            Response.ContentType = "application/json";
            await Response.WriteAsync(JsonConvert.SerializeObject(res, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
Beispiel #22
0
        public async Task CreateCompany([FromForm] Company company, [FromForm] IFormFile[] uploadedFile = null)
        {
            //var file = HttpContext.Request.Form.Files;

            string userId = AuthJWT.GetCurrentId(HttpContext, out int statusId);

            if (statusId != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return;
            }

            if (!ModelState.IsValid)
            {
                Response.StatusCode = 400;
                return;
            }

            var newCompany = await Company.Create(_db, _appEnvironment, userId, company, uploadedFile);

            //Company newCompany = new Company(company.Name, company.Description, company.Number, company.Email);
            //newCompany.Validation(new ValidationInput());

            //_db.Companys.Add(newCompany);
            //await _db.SaveChangesAsync();

            //await newCompany.SetImage(_db, uploadedFile, _appEnvironment);

            //_db.CompanyUsers.Add(new Models.Domain.ManyToMany.CompanyUser(userId, newCompany.Id, StatusInCompany.Moderator));
            //await _db.SaveChangesAsync();
            //return newCompany;
            Response.ContentType = "application/json";

            await Response.WriteAsync(JsonConvert.SerializeObject(new { newCompany.Id, newCompany.Name }, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
Beispiel #23
0
        public async Task <bool?> AddUserToCompany([FromForm] int companyId, [FromForm] string newUserId, [FromForm] StatusInCompany newStatus)
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int statusId);

            if (statusId != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return(null);
            }
            var company = await Company.GetIfAccess(_db, userId, companyId);

            if (company == null)
            {
                Response.StatusCode = 404;
                return(null);
            }
            bool?res = null;

            if (newStatus == StatusInCompany.Moderator)
            {
                res = await company.AddHeadUser(_db, newUserId);
            }
            if (newStatus == StatusInCompany.Employee)
            {
                //#TODO
                //res = await company.AddHeadUser(_db, newUserId);
            }

            if (res == null)
            {
                Response.StatusCode = 527;
                return(null);
            }

            return(res);
        }
Beispiel #24
0
        public async Task Register([FromForm] RegisterModel model)//, string confirmPassword
        {
            if (!ModelState.IsValid)
            {
                Response.StatusCode = 400;
                return;
            }

            var user = new ApplicationUser {
                UserName = model.Email, Email = model.Email
            };

            user.Validation(new ValidationInput());
            var result = await _userManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                Response.StatusCode = 404;
                return;
            }


            var identity = AuthJWT.GetIdentity(user);

            if (identity == null)
            {
                Response.StatusCode = 500;
                // await Response.WriteAsync("Invalid username or password.");
                return;
            }

            var encodedJwt    = AuthJWT.GenerateMainToken(identity);
            var encodedRefJwt = AuthJWT.GenerateRefreshToken();
            await user.SetRefreshToken(_db, encodedRefJwt);


            //--------этот блок для подтверждения почты
            //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            //var callbackUrl = Url.Action(
            //    "ConfirmEmail",
            //    "Account",
            //    new { userId = user.Id, code = code },
            //    protocol: HttpContext.Request.Scheme);
            //EmailService emailService = new EmailService();
            //await emailService.SendEmailAsync(model.Email, "Confirm your account",
            //    $"Подтвердите регистрацию, перейдя по ссылке: <a href='{callbackUrl}'>link</a>");

            var response = new
            {
                access_token  = encodedJwt,
                refresh_token = encodedRefJwt,
                username      = identity.Name
            };


            // сериализация ответа
            Response.ContentType = "application/json";

            await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
Beispiel #25
0
 public async Task <bool> LogOut([FromForm] string userId, [FromForm] string refreshToken)
 {
     return(await AuthJWT.DeleteRefreshTokenFromDb(_db, userId, refreshToken));
 }
Beispiel #26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));



            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.ClaimsIdentity.UserIdClaimType = ClaimsIdentity.DefaultNameClaimType;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();
            //services.AddTransient<UserManager<ApplicationUser>>();



            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;  //TODO надо поставить true для ssl
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // укзывает, будет ли валидироваться издатель при валидации токена
                    ValidateIssuer = true,
                    // строка, представляющая издателя
                    ValidIssuer = AuthJWT.ISSUER,

                    // будет ли валидироваться потребитель токена
                    ValidateAudience = true,
                    // установка потребителя токена
                    ValidAudience = AuthJWT.AUDIENCE,
                    // будет ли валидироваться время существования
                    ValidateLifetime = true,

                    // установка ключа безопасности
                    IssuerSigningKey = AuthJWT.GetSymmetricSecurityKey(),
                    // валидация ключа безопасности
                    ValidateIssuerSigningKey = true,
                };
            });



            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Version        = "v1",
                    Title          = "ProjectRecruting",
                    Description    = "service for students",
                    TermsOfService = "None",
                    Contact        = new Swashbuckle.AspNetCore.Swagger.Contact
                    {
                        Name = "yeap", Email = "@zsuzitor", Url = ""
                    }
                });
                //var xmlFile = "swaggerxmlsettings.xml";
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
        }
Beispiel #27
0
 public async Task SetRefreshToken(ApplicationDbContext db, string token)
 {
     this.RefreshTokenHash = AuthJWT.GetHashRefreshToken(token);//token.GetHashCode();
     await db.SaveChangesAsync();
 }
Beispiel #28
0
        public async Task <bool> ChangeProject([FromForm] Project project, [FromForm] int[] deleteImages,
                                               [FromForm] string[] competences, [FromForm] int[] competenceIds, [FromForm] IFormFile[] uploadedFile = null)
        {
            string userId = AuthJWT.GetCurrentId(HttpContext, out int statusId);

            if (statusId != 0 || userId == null)
            {
                Response.StatusCode = 401;
                return(false);
            }

            if (!ModelState.IsValid)
            {
                Response.StatusCode = 404;
                return(false);
            }
            project.Validation(new ValidationInput());
            var oldProj = await ApplicationUser.CheckAccessEditProject(_db, project.Id, userId);

            if (oldProj == null)
            {
                Response.StatusCode = 404;
                return(false);
            }

            var updt = await oldProj.Update(_db, _appEnvironment, project, competences, competenceIds, uploadedFile, deleteImages);

            if (updt == null)
            {
                Response.StatusCode = 527;
                return(false);
            }

            //using (var tranzaction = _db.Database.BeginTransaction())
            //{
            //    try
            //    {

            //        oldProj.ChangeData(project.Name, project.Description, project.Payment);
            //        await _db.SaveChangesAsync();
            //        await oldProj.AddCompetences(_db, competences);
            //        await oldProj.DeleteCompetences(_db, competenceIds);
            //        await Project.DeleteImagesFromDb(_db, oldProj.Id, deleteImages);
            //        tranzaction.Commit();
            //    }
            //    catch (DbUpdateConcurrencyException ex)
            //    {
            //        tranzaction.Rollback();
            //        Response.StatusCode = 527;
            //        return false;
            //    }
            //    catch
            //    {
            //        tranzaction.Rollback();
            //        return false;
            //    }
            //}

            //await oldProj.AddImagesToDbSystem(_db, _appEnvironment, uploadedFile);

            return(true);
        }