示例#1
0
        public async Task <ActionResult> CheckDeviceActiveAsync([FromBody] ConsumerAuthRequest req)
        {
            try
            {
                var device = await _dbContext.Devices.Where(d => d.Id == req.Device.Id).FirstOrDefaultAsync();


                if (device != null)
                {
                    if (device.IsActive)
                    {
                        return(Ok());
                    }
                    else
                    {
                        return(BadRequest());
                    }
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, "Device Checking Throws", req);
                return(BadRequest());
            }
        }
示例#2
0
        public async Task <ActionResult> RegisterConsumerAsync([FromBody] ConsumerAuthRequest req)
        {
            try
            {
                var secretKey = _configuration["SecurityKey"];
                var device    = req.Device;
                device.IsActive = true;
                string roomId    = Guid.NewGuid().ToString();
                var    tokenInfo = new LoginInfo {
                    DeviceId = device.Id, DeviceType = device.DeviceType
                };
                var user = await _dbContext.Users
                           .Where(u => u.Name == req.User.Name)
                           .Where(u => u.BirthDate.Date == req.User.BirthDate.Date)
                           .Where(u => u.Gender == req.User.Gender)
                           .Where(u => u.Email == req.User.Email)
                           .Include(u => u.Devices)
                           .Include(u => u.Enrollments)
                           .FirstOrDefaultAsync();

                if (user != null) // user already exists...
                {
                    // 방금 입력한 비밀번호로 로그인 되면
                    if (_userService.VerifyPasswordHash(req.User.Password, user.PasswordHash, user.PasswordSalt))
                    {
                        // 이전 기기들 비활성화
                        foreach (var d in user.Devices)
                        {
                            d.IsActive = false;
                        }

                        if (!user.Devices.Any(d => d.Id == device.Id))
                        {
                            if (await _dbContext.Devices.FirstOrDefaultAsync(d => d.Id == device.Id) is Device deviceBelogsOther)
                            {
                                deviceBelogsOther.Owner    = user;
                                deviceBelogsOther.IsActive = true;
                                deviceBelogsOther.IsOn     = true;
                            }
                            else
                            {
                                user.Devices.Add(device);
                            }
                        }
                        else
                        {
                            var userDevice = user.Devices.FirstOrDefault(d => d.Id == device.Id);
                            userDevice.IsActive = true;
                            userDevice.IsOn     = true;
                        }

                        if (user.Enrollments.Any())
                        {
                            roomId = user.Enrollments.First().RoomId;
                        }
                        else
                        {
                            var room = new Room {
                                Name = user.Name, Id = roomId
                            };
                            user.Enrollments.Add(new Enrollment {
                                Room = room, EnrolledAt = DateTime.UtcNow
                            });
                        }

                        await _dbContext.SaveChangesAsync();

                        // 이미 허브에 접속해있는 기기에 퇴출 신호
                        var userProxy = _hubContext.Clients.User(user.Id.ToString());
                        await userProxy.SendAsync("NewLogin", device.Id);

                        return(Ok(new ConsumerAuthResponse
                        {
                            RoomId = roomId,
                            UserId = user.Id,
                            UserName = user.Name,
                            Success = true,
                            IsAlreadyRegistered = true,
                            Token = user.JwtToken(tokenInfo, secretKey)
                        }));;

                        // TODO: App.Startup()에서 Device의 활성 상태 검증
                        // 비활성 기기면 재로그인
                    }
                    else // Name, BirthDate, Sex, Email은 일치하지만 비번이 틀림
                    {
                        // TODO: 비밀번호 재입력 및 재설정 안내
                        // 신모법님은 링거에 가입되어 있지만 비밀번호가 틀렸습니다. 정확한 비밀번호를 입력하세요.
                        // 여기를 누르면 계정이메일([email protected])으로 비밀번호 재설정 링크를 발송합니다.
                        // [email protected]으로 비밀번호 재설정 링크를 발송했습니다.
                        return(Unauthorized(new ConsumerAuthResponse
                        {
                            Success = false,
                            RequireLogin = true
                        }));;
                    }
                }
                else
                {
                    var createdUser = await _userService.CreateAsync(req.User, req.User.Password);

                    user = await _dbContext.Users
                           .Include(u => u.Devices)
                           .Include(u => u.Enrollments)
                           .FirstOrDefaultAsync(u => u.Id == createdUser.Id);

                    // add device
                    user.Devices.Add(device);

                    // add enrollment / room
                    var room = new Room {
                        Id = roomId, Name = user.Name
                    };
                    user.Enrollments.Add(new Enrollment {
                        Room = room, EnrolledAt = DateTime.UtcNow
                    });

                    await _dbContext.SaveChangesAsync();

                    return(Ok(new ConsumerAuthResponse
                    {
                        RoomId = room.Id,
                        UserId = user.Id,
                        UserName = user.Name,
                        Success = true,
                        Token = user.JwtToken(tokenInfo, secretKey)
                    }));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, "Consumer Registration Throws", req);
                return(StatusCode(500));
            }
        }
示例#3
0
        public async Task <ActionResult> LoginConsumerAsync([FromBody] ConsumerAuthRequest req)
        {
            try
            {
                var secretKey = _configuration["SecurityKey"];
                var device    = req.Device;
                device.IsActive = true;
                string roomId    = Guid.NewGuid().ToString();
                var    tokenInfo = new LoginInfo {
                    DeviceId = device.Id, DeviceType = device.DeviceType
                };
                var user = await _dbContext.Users
                           .Where(u => u.Email == req.User.Email)
                           .Include(u => u.Devices)
                           .Include(u => u.Enrollments)
                           .FirstOrDefaultAsync();

                if (user != null)
                {
                    // 방금 입력한 비밀번호로 로그인 되면
                    if (_userService.VerifyPasswordHash(req.User.Password, user.PasswordHash, user.PasswordSalt))
                    {
                        // 이전 기기들 비활성화
                        foreach (var d in user.Devices.Where(d => d.Id != device.Id))
                        {
                            d.IsActive = false;
                            d.IsOn     = false;
                        }

                        if (!user.Devices.Any(d => d.Id == device.Id))
                        {
                            if (await _dbContext.Devices.FirstOrDefaultAsync(d => d.Id == device.Id) is Device deviceBelogsOther)
                            {
                                deviceBelogsOther.Owner    = user;
                                deviceBelogsOther.IsActive = true;
                                deviceBelogsOther.IsOn     = true;
                            }
                            else
                            {
                                user.Devices.Add(device);
                            }
                        }
                        else
                        {
                            var userDevice = user.Devices.FirstOrDefault(d => d.Id == device.Id);
                            userDevice.IsActive = true;
                            userDevice.IsOn     = true;
                        }

                        if (user.Enrollments.Any())
                        {
                            roomId = user.Enrollments.First().RoomId;
                        }
                        else
                        {
                            var room = new Room {
                                Name = user.Name, Id = roomId
                            };
                            user.Enrollments.Add(new Enrollment {
                                Room = room, EnrolledAt = DateTime.UtcNow
                            });
                        }

                        await _dbContext.SaveChangesAsync();

                        // 이미 허브에 접속해있는 기기에 퇴출 신호
                        var userProxy = _hubContext.Clients.User(user.Id.ToString());
                        await userProxy.SendAsync("NewLogin", device.Id);

                        return(Ok(new ConsumerAuthResponse
                        {
                            RoomId = roomId,
                            UserId = user.Id,
                            UserName = user.Name,
                            Token = user.JwtToken(tokenInfo, secretKey),
                            Success = true,
                        }));

                        // TODO: App.Startup()에서 Device의 활성 상태 검증
                        // 비활성 기기면 재로그인
                    }
                    else // Name, BirthDate, Sex, Email은 일치하지만 비번이 틀림
                    {
                        return(Unauthorized(new ConsumerAuthResponse
                        {
                            Success = false,
                            RequireLogin = true,
                            ErrorMessage = "비밀번호가 틀렸습니다."
                        }));
                    }
                }
                else
                {
                    return(BadRequest(new ConsumerAuthResponse
                    {
                        Success = false,
                        ErrorMessage = $"입력한 이메일({req.User.Email})이 등록되어있지 않습니다."
                    }));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, "Consumer Login Throws", req);
                return(StatusCode(500, new ConsumerAuthResponse
                {
                    Success = false,
                    ErrorMessage = $"서버에서 에러가 일어났습니다."
                }));
            }
        }