private async Task <bool> CheckAccount(ServicesModel.Models.Auth.Auth auth)
        {
            try
            {
                var check = await _context.Auths.Where(x => (x.Phone == auth.Phone && x.email == auth.email && x.role == auth.role)).FirstOrDefaultAsync();

                if (check == null)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            catch (Exception e) {
                return(false);
            }
        }
        public async Task <ActionResult> AuthorizeFromPhone([FromBody] SendRegister token)
        {
            var user = await _context.Auths.Where(x => x.role == token.role && x.Phone == token.phone).FirstOrDefaultAsync();

            if (user != null)
            {
                return(BadRequest());
            }
            user = new ServicesModel.Models.Auth.Auth
            {
                data_add       = DateTime.Now,
                last_visit     = DateTime.Now,
                is_active      = true,
                role           = token.role,
                password       = "******",
                email          = token.email,
                EmailConfirmed = false,
                UserName       = token.email,
                Phone          = token.phone
            };
            await _context.Auths.AddAsync(user);

            await _context.SaveChangesAsync();

            UID uid = new UID
            {
                uid        = token.id,
                id_user    = user.id,
                updateDttm = DateTime.Now
            };
            await _context.Uids.AddAsync(uid);

            var new_token = _auth.Generate_Tokens(user.id, user.role);
            await _context.Tokens.AddAsync(new_token);

            user.last_visit = DateTime.Now;
            ServicesModel.Models.Account.Account account = new ServicesModel.Models.Account.Account
            {
                address = token.address,
                name    = token.name,
                email   = token.email,
                id_user = user.id,
                phone   = token.phone,
                site    = token.site,
                update  = DateTime.Now
            };
            await _context.Accounts.AddAsync(account);

            await _context.SaveChangesAsync();

            foreach (var acc in token.level1)
            {
                var category = new CategoryAccount
                {
                    id_account = account.id,
                    level0     = token.level0,
                    level1     = acc
                };
                await _context.categoryAccounts.AddAsync(category);
            }
            await _context.SaveChangesAsync();

            return(Ok(new_token.access));
        }
        public async Task <JsonResult> PostAuth([FromBody] Register auth)
        {
            if (ModelState.IsValid)
            {
                Token    token = null;
                SendAuth send  = null;
                try
                {
                    var check = CheckEmail(auth.email);

                    ServicesModel.Models.Auth.Auth authtemp = new ServicesModel.Models.Auth.Auth
                    {
                        data_add   = DateTime.Now,
                        last_visit = DateTime.Now,
                        is_active  = true,
                        role       = auth.role,
                        password   = auth.password
                    };
                    ServicesModel.Models.Account.Account account = new ServicesModel.Models.Account.Account
                    {
                        update = DateTime.Now
                    };
                    if (check == "phone")
                    {
                        authtemp.UserName = auth.email;
                        authtemp.Phone    = auth.email;
                        account.phone     = auth.email;
                    }
                    else if (check == "email")
                    {
                        authtemp.email    = auth.email;
                        authtemp.UserName = auth.email;
                        account.email     = auth.email;
                    }
                    else
                    {
                        return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.BadRequest, null, "Укажите номер телефона или почты в правильном формате")));
                    }

                    if (!await CheckAccount(authtemp))
                    {
                        authtemp.is_active = true;
                        await _context.Auths.AddAsync(authtemp);

                        //   var result=await _manager.CreateAsync(authtemp, auth.password);
                        //if (result.Succeeded)
                        //{
                        //    var currentUser = await _manager.FindByNameAsync(auth.email);

                        //    var roleresult = _manager.AddToRoleAsync(authtemp, "owner");
                        //}
                        //else
                        //{
                        //    string error = "";
                        //    foreach (var s in result.Errors.ToList())
                        //    {
                        //        error += s.Description + "\n";
                        //    }
                        //    return new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.Conflict, null,
                        //        error));

                        //}
                        await _context.SaveChangesAsync();

                        var id = await _context.Auths.Where(x => x.email == authtemp.email && x.Phone == authtemp.Phone).Select(x => x.id).FirstOrDefaultAsync();

                        token           = _auth.Generate_Tokens(id, auth.role);
                        account.id_user = id;
                        await _context.Accounts.AddAsync(account);

                        await _context.Tokens.AddAsync(token);

                        if (check == "email")
                        {
                            await _auth.Confirm(id, authtemp.email);
                        }
                        await _context.SaveChangesAsync();

                        var accountsend = await _context.Accounts.Where(x => x.id_user == id).FirstOrDefaultAsync();

                        send = new SendAuth
                        {
                            accountid = accountsend.id,
                            token     = token.access,
                            role      = authtemp.role
                        };
                    }
                    else
                    {
                        return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.Forbidden, null, "Такой email уже зарегистрирован")));
                    }
                }
                catch (Exception ex)
                {
                    return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.Conflict, null, "Такой email уже зарегистрирован")));
                }
                return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.Created, send, null)));
            }

            return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.BadRequest, null, "Неправильные данные")));
        }
        public async Task <JsonResult> PostAuthClient([FromBody] Register auth)
        {
            if (ModelState.IsValid)
            {
                Token    token = null;
                SendAuth send  = null;
                try
                {
                    var check = CheckEmail(auth.email);

                    ServicesModel.Models.Auth.Auth authtemp = new ServicesModel.Models.Auth.Auth
                    {
                        data_add       = DateTime.Now,
                        last_visit     = DateTime.Now,
                        is_active      = true,
                        role           = auth.role,
                        password       = auth.password,
                        email          = auth.email,
                        EmailConfirmed = false,
                        UserName       = auth.email,
                    };

                    Client client;

                    if (!await CheckAccount(authtemp))
                    {
                        authtemp.is_active  = true;
                        authtemp.last_visit = DateTime.Now;
                        await _context.Auths.AddAsync(authtemp);

                        await _context.SaveChangesAsync();

                        client = new Client
                        {
                            update_date = DateTime.Now,
                            id_user     = authtemp.id,
                            email       = auth.email,
                            status      = "manual"
                        };

                        //await _context.SaveChangesAsync();
                        //    var id = await _context.Auths.Where(x => x.email == authtemp.email && x.Phone == authtemp.Phone).Select(x => x.id).FirstOrDefaultAsync();
                        token = _auth.Generate_Tokens(authtemp.id, auth.role);

                        await _context.Clients.AddAsync(client);

                        await _context.Tokens.AddAsync(token);

                        if (check == "email")
                        {
                            await _auth.Confirm(authtemp.id, authtemp.email);
                        }
                        await _context.SaveChangesAsync();

                        send = new SendAuth
                        {
                            accountid = client.id,
                            token     = token.access
                        };
                    }
                    else
                    {
                        return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.Forbidden, null, "Такой email уже зарегистрирован")));
                    }
                }
                catch (Exception ex)
                {
                    return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.Conflict, null, "Такой email уже зарегистрирован")));
                }
                return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.Created, send, null)));
            }

            return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.BadRequest, null, "Неправильные данные")));
        }
        public async Task <ActionResult> CheckCode([FromBody] CheckCode phone)
        {
            if (ModelState.IsValid)
            {
                var code = (from aa in _context.SMSCodes
                            join bb in _context.Auths on aa.phone equals bb.Phone
                            where aa.phone == phone.phone && aa.code == phone.code && aa.dttm_add.AddMinutes(5) > DateTime.Now
                            select aa).FirstOrDefault();

                if (code == null)
                {
                    return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.NotFound, null,
                                                                    "Телефон не подтвержден")));
                }
                else
                {
                    var user = await _context.Auths.Where(x => x.Phone == phone.phone).ToListAsync();

                    Token token = null;
                    if (user.Count != 0)
                    {
                        var uid = new UID
                        {
                            updateDttm = DateTime.Now,
                            uid        = phone.id,
                        };
                        ServicesModel.Models.Auth.Auth findUser = null;
                        if (user.Exists(x => x.role == "owner"))
                        {
                            findUser = user.Find(x => x.role == "owner");
                        }
                        else
                        {
                            findUser = user.Find(x => x.role == "staff");
                        }
                        token = await _context.Tokens.Where(x => x.user_id == findUser.id).FirstAsync();

                        _context.Remove(token);
                        token = _auth.Generate_Tokens(findUser.id, findUser.role);
                        await _context.Tokens.AddAsync(token);

                        uid.id_user = findUser.id;
                        await _context.Uids.AddAsync(uid);

                        var send = await _account.ReturnAuth(findUser.id, findUser.role);

                        await _context.SaveChangesAsync();

                        return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.OK, send,
                                                                        "Пользователь найден")));
                    }
                    else
                    {
                        return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.NoContent, null,
                                                                        "Код подтвержден")));
                    }
                }
            }

            else
            {
                return(new JsonResult(_responce.Return_Responce(System.Net.HttpStatusCode.BadRequest, null,
                                                                "Не заполнено")));
            }
        }