Пример #1
0
 public function beforeCreate()
 {
     $user = new LoginModel();
     if ($userinfo = $user->isUserLoggedIn()) {
         $this->userId = $userinfo['id'];
         $this->username = $userinfo['username'];
     }
 }
Пример #2
0
 public function beforeUpdate()
 {
     $user = new LoginModel();
     if ($userinfo = $user->isUserLoggedIn()) {
         $this->editorId = $userinfo['id'];
         $this->editorName = $userinfo['username'];
     }
     $this->updatedAt = time();
 }
Пример #3
0
 public function beforeCreate()
 {
     $this->createdAt = $this->updatedAt = time();
     $user = new LoginModel();
     if ($userinfo = $user->isUserLoggedIn()) {
         $this->userId = $this->userId ? $this->userId : $userinfo['id'];
         $this->username = $this->username ? $this->username : $userinfo['username'];
     }
 }
Пример #4
0
 private function getUserInfo()
 {
     $user = new LoginModel();
     if ($user->isUserLoggedIn()) {
         $userinfo = $user->getCurrentUser();
         return $userinfo;
     } else {
         return false;
     }
 }
Пример #5
0
 public function beforeUpdate()
 {
     $this->updatedAt = $this->updatedAt ?: time();
     $user = new LoginModel();
     if ($user->isUserLoggedIn()) {
         $userinfo = LoginModel::getCurrentUser();
         $this->userId = $this->userId ? $this->userId : $userinfo['id'];
         $this->username = $this->username ? $this->username : $userinfo['username'];
     }
 }
Пример #6
0
 public function testAction()
 {
     $user = new Models\Login();
     $authIdentity = $user->getAuthIdentity();
     if (!$authIdentity && ($tokenString = $this->cookies->get('realm')->getValue())) {
         if ($user->loginByCookie($tokenString)) {
         } else {
             $this->cookies->delete('realm');
         }
     }
 }
Пример #7
0
 public function connectWithPassword($identify, $password, array $accessToken)
 {
     $userModel = new UserLogin();
     $user = $userModel->loginByPassword($identify, $password);
     $accessTokenEntity = new AccessTokens();
     $accessTokenEntity->assign($accessToken);
     $accessTokenEntity->tokenStatus = 'active';
     $accessTokenEntity->userId = $user->id;
     if (!$accessTokenEntity->save()) {
         throw new Exception\RuntimeException('ERR_OAUTH_TOKEN_CREATE_FAILED');
     }
     return $user;
 }
Пример #8
0
 /**
  *
  * @SWG\Api(
  *   path="/users/me",
  *   description="User API",
  *   produces="['application/json']",
  *   @SWG\Operations(
  *     @SWG\Operation(
  *       method="GET",
  *       summary="Get current user info",
  *     )
  *   )
  * )
  */
 public function indexAction()
 {
     Login::setLoginMode(Login::LOGIN_MODE_TOKEN);
     $storage = Login::getAuthStorage();
     $userinfo = Login::getCurrentUser();
     return $this->response->setJsonContent($userinfo);
 }
Пример #9
0
 public function afterLogin($event, $loginUser)
 {
     if (!$loginUser->id) {
         return;
     }
     $storage = Login::getAuthStorage();
     if (Login::getLoginMode() == Login::LOGIN_MODE_TOKEN) {
         $apikey = new Apikey();
         $userId = $loginUser->id;
         $token = $apikey->findFirst("userId = {$userId}");
         if (!$token) {
             $token = $apikey->generateToken($userId);
         }
         $storage->setId($token->apikey);
         $storage->set(Login::AUTH_KEY_TOKEN, $token);
     }
     $defaultRoles = $loginUser->getRoles();
     $roles = $loginUser->roles;
     $authRoles = array();
     if ($roles) {
         foreach ($roles as $role) {
             $authRoles[] = $role->roleKey;
         }
     }
     $authRoles = array_unique(array_merge($defaultRoles, $authRoles));
     $storage->set(Login::AUTH_KEY_ROLES, $authRoles);
 }
Пример #10
0
 public function indexAction()
 {
     $this->cookies->delete('realm');
     Login::removeBadges();
     $this->getDI()->get('session')->remove('auth-identity');
     $this->view->disable();
     return $this->response->redirect('/admin');
 }
Пример #11
0
 public function indexAction()
 {
     $this->cookies->delete(Login::LOGIN_COOKIE_KEY);
     $this->cookies->delete(Login::LOGIN_COOKIE_REMEMBER_KEY);
     Login::getAuthStorage()->remove(Login::AUTH_KEY_LOGIN);
     Login::getAuthStorage()->remove(Login::AUTH_KEY_TOKEN);
     Login::getAuthStorage()->remove(Login::AUTH_KEY_ROLES);
     return $this->response->redirect('/');
 }
Пример #12
0
 /**
  *
  * @SWG\Api(
  *   path="/login",
  *   description="User Login API",
  *   produces="['application/json']",
  *   @SWG\Operations(
  *     @SWG\Operation(
  *       method="POST",
  *       summary="Login by password",
  *       @SWG\Parameters(
  *         @SWG\Parameter(
  *           name="Login json",
  *           description="{ identify : username or email, password : password}",
  *           paramType="body",
  *           required=true,
  *           type="string"
  *         )
  *       )
  *     )
  *   )
  * )
  */
 public function indexAction()
 {
     Login::setLoginMode(Login::LOGIN_MODE_TOKEN);
     $data = $this->request->getRawBody();
     if (!$data) {
         throw new Exception\InvalidArgumentException('No data input');
     }
     if (!($data = json_decode($data, true))) {
         throw new Exception\InvalidArgumentException('Json data parsing failed');
     }
     $form = new LoginForm();
     if ($form->isValid($data) === false) {
         return $this->showInvalidMessagesAsJson($form);
     }
     $user = new Login();
     $apikey = new Apikey();
     $loginUser = $user->loginByPassword($data['identify'], $data['password']);
     $userinfo = $loginUser->dump(User::$simpleDump);
     $userinfo['roles'] = Login::getAuthStorage()->get(Login::AUTH_KEY_ROLES);
     $userinfo['token'] = Login::getAuthStorage()->get(Login::AUTH_KEY_TOKEN);
     return $this->response->setJsonContent($userinfo);
 }
Пример #13
0
 public function requestChangeEmail($newEmail, $forceSend = false)
 {
     $me = Login::getCurrentUser();
     $userId = $me['id'];
     if (!$userId) {
         throw new Exception\UnauthorizedException('ERR_USER_NOT_LOGIN');
     }
     $user = self::findFirst("id = {$userId}");
     if (!$user) {
         throw new Exception\ResourceNotFoundException('ERR_USER_NOT_EXIST');
     }
     return $this->sendChangeEmailVerificationEmail($user->username, $newEmail);
 }
Пример #14
0
 public function getRoles()
 {
     $user = Login::getCurrentUser();
     if (!$user['id']) {
         return array('GUEST');
     }
     $storage = Login::getAuthStorage();
     $authRoles = $storage->get(Login::AUTH_KEY_ROLES);
     $authRoles = $authRoles ?: array();
     //Add default roles
     if ($user['status'] == 'active') {
         $authRoles[] = 'USER';
         $authRoles = array_unique($authRoles);
     }
     return $authRoles;
 }
Пример #15
0
 public function checkAction()
 {
     $username = $this->request->get('username');
     $email = $this->request->get('email');
     if ($username) {
         $userinfo = Models\Login::findFirst(array("username = '******'"));
     } elseif ($email) {
         $userinfo = Models\Login::findFirst(array("email = '{$email}'"));
     } else {
         $userinfo = array();
     }
     $this->view->disable();
     if ($userinfo) {
         $this->response->setStatusCode('409', 'User Already Exists');
     }
     return $this->response->setJsonContent(array('exist' => $userinfo ? true : false, 'id' => $userinfo ? $userinfo->id : 0, 'status' => $userinfo ? $userinfo->status : null));
 }
Пример #16
0
 /**
  * @operationName("users mobile binding")
  * @operationDescription("users mobile binding")
  */
 public function bindMobileAction()
 {
     $bindingForm = new MobileBindingForm(new User());
     $curUser = Login::getCurrentUser();
     $data = $this->request->getPut();
     $data['userId'] = $curUser['id'];
     if (!$bindingForm->isValid($data)) {
         return $this->showInvalidMessagesAsJson($bindingForm);
     }
     try {
         if (!User::bindMobile($data['mobile'], $data['captcha'], $data['userId'])) {
             return $this->showErrorMessageAsJson(400, 'BIND_MOBILE_FAILURE');
         }
     } catch (Exception\LogicException $e) {
         return $this->showExceptionAsJson($e);
     }
     return $this->showResponseAsJson(['mobile' => $data['mobile'], 'status' => true]);
 }
Пример #17
0
 /**
  * @operationName("取消收藏文章")
  * @operationDescription("取消收藏文章")
  */
 public function deleteAction()
 {
     $user = Login::getCurrentUser();
     $userId = $user['id'];
     $postId = $this->dispatcher->getParam('id', 'int');
     if ($userId < 1 || $postId < 1) {
         return;
     }
     $star = Stars::findFirst("userId = {$userId} AND postId = {$postId}");
     if ($star) {
         $star->delete();
     } else {
         $star = new Stars();
         $star->userId = $userId;
         $star->postId = $postId;
     }
     return $this->response->setJsonContent($star);
 }
Пример #18
0
 public function indexAction()
 {
     if (!$this->request->isPost()) {
         return;
     }
     if ($this->request->isAjax()) {
         $form = new Forms\LoginForm();
         if ($form->isValid($this->request->getPost()) === false) {
             return $this->showInvalidMessagesAsJson($form);
         }
         $user = new Login();
         try {
             $loginUser = $user->loginByPassword($this->request->getPost('identify'), $this->request->getPost('password'));
             if ($this->request->getPost('remember')) {
                 $token = $user->getRememberMeToken();
                 if ($token) {
                     $this->cookies->set(Login::LOGIN_COOKIE_REMEMBER_KEY, $token, time() + $user->getRememberMeTokenExpires());
                 }
             }
             return $this->showResponseAsJson(Login::getCurrentUser());
         } catch (\Exception $e) {
             return $this->showExceptionAsJson($e, $user->getMessages());
         }
     } else {
         $form = new Forms\LoginForm();
         if ($form->isValid($this->request->getPost()) === false) {
             $this->showInvalidMessages($form);
             return $this->redirectHandler($this->getDI()->getConfig()->user->loginFailedRedirectUri, 'error');
         }
         $user = new Login();
         try {
             $user->loginByPassword($this->request->getPost('identify'), $this->request->getPost('password'));
             if ($this->request->getPost('remember')) {
                 $token = $user->getRememberMeToken();
                 if ($token) {
                     $this->cookies->set('realm', $token, time() + $user->getRememberMeTokenExpires());
                 } else {
                     $this->flashSession->error($user->getMessages());
                 }
             }
             //$this->flashSession->success('SUCCESS_USER_LOGGED_IN');
             return $this->redirectHandler($this->getDI()->getConfig()->user->loginSuccessRedirectUri);
         } catch (\Exception $e) {
             $this->showException($e, $user->getMessages());
             return $this->redirectHandler($this->getDI()->getConfig()->user->loginFailedRedirectUri, 'error');
         }
     }
 }
Пример #19
0
 /**
  * @param $validator
  * @param string $attribute
  * @return bool
  */
 public function validate($validator, $attribute)
 {
     $value = $validator->getValue($attribute);
     $usr = Login::getCurrentUser();
     if (!$usr['id']) {
         $validator->appendMessage(new Validation\Message('ERR_USER_NOT_LOGIN', $attribute));
         return false;
     }
     /**
      * @var $usr User
      */
     $usr = User::findFirst('id = ' . $usr['id']);
     if (!Login::passwordVerify($value, $usr->password)) {
         $message = $this->getOption('message');
         if (!$message) {
             //$message = 'The old password provided is incorrect.';
             $message = 'ERR_USER_OLD_PASSWORD_NOT_MATCH';
         }
         $validator->appendMessage(new Validation\Message($message, $attribute, null, null));
         return false;
     }
     return true;
 }
Пример #20
0
 public function indexAction()
 {
     return $this->response->setJsonContent(Login::getCurrentUser());
 }
Пример #21
0
 public function indexAction()
 {
     if (!$this->request->isPost()) {
         return;
     }
     if ($this->request->isAjax() || $this->request->get('ajax')) {
         $form = new Forms\LoginForm();
         if ($form->isValid($this->request->getPost()) === false) {
             return $this->showInvalidMessagesAsJson($form);
         }
         $user = new Login();
         try {
             $loginUser = $user->loginByPassword($this->request->getPost('identify'), $this->request->getPost('password'));
             $cookieDomain = $this->getDI()->getConfig()->session->sso_domain;
             if ($loginUser->id && $this->request->getPost('remember')) {
                 $token = $user->getRememberMeToken();
                 if ($token) {
                     $cookies = $this->cookies->set(Login::LOGIN_COOKIE_REMEMBER_KEY, $token, time() + $user->getRememberMeTokenExpires());
                     if ($cookieDomain) {
                         $cookie = $cookies->get(Login::LOGIN_COOKIE_REMEMBER_KEY);
                         $cookie->setDomain($cookieDomain);
                     }
                 }
             }
             if (!empty($_SERVER['HTTP_ORIGIN'])) {
                 $this->response->setHeader('Access-Control-Allow-Credentials', 'true');
                 $this->response->setHeader('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN']);
                 $this->response->setHeader('Access-Control-Allow-Methods', 'POST');
                 $this->response->setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
             }
             return $this->showResponseAsJson(Login::getCurrentUser());
         } catch (\Exception $e) {
             return $this->showExceptionAsJson($e, $user->getMessages());
         }
     } else {
         $loginFailedRedirectUri = $this->dispatcher->getParam('loginFailedRedirectUri');
         $loginFailedRedirectUri = $loginFailedRedirectUri ? $loginFailedRedirectUri : $this->getDI()->getConfig()->user->loginFailedRedirectUri;
         $loginFailedRedirectUri = $loginFailedRedirectUri ? $loginFailedRedirectUri : $this->request->getURI();
         $form = new Forms\LoginForm();
         if ($form->isValid($this->request->getPost()) === false) {
             $this->showInvalidMessages($form);
             return $this->redirectHandler($loginFailedRedirectUri, 'error');
         }
         $user = new Login();
         try {
             $user->loginByPassword($this->request->getPost('identify'), $this->request->getPost('password'));
             if ($this->request->getPost('remember')) {
                 $token = $user->getRememberMeToken();
                 if ($token) {
                     $ssoDomain = $this->getDI()->getConfig()->session->sso_domain;
                     $this->cookies->set('realm', $token, time() + $user->getRememberMeTokenExpires());
                     if ($ssoDomain) {
                         $cookie = $this->cookies->get(Login::LOGIN_COOKIE_REMEMBER_KEY);
                         $cookie->setDomain($ssoDomain);
                     }
                 } else {
                     $this->flashSession->error($user->getMessages());
                 }
             }
             //$this->flashSession->success('SUCCESS_USER_LOGGED_IN');
             $loginSuccessRedirectUri = $this->dispatcher->getParam('loginSuccessRedirectUri');
             if (empty($loginSuccessRedirectUri)) {
                 $loginSuccessRedirectUri = '/';
             }
             return $this->response->redirect($loginSuccessRedirectUri);
         } catch (\Exception $e) {
             $this->showException($e, $user->getMessages());
             // $this->getDI()->getConfig()->user->loginFailedRedirectUri
             return $this->response->redirect($loginFailedRedirectUri, 'error');
         }
     }
 }
Пример #22
0
 /**
  * @operationName("用户收藏文章列表")
  * @operationDescription("用户收藏文章列表")
  */
 public function starsAction()
 {
     $me = Login::getCurrentUser();
     $user = User::findFirstById($me['id']);
     $this->view->setVar('item', $user);
     $userId = $user->id;
     $query = array('page' => $this->request->getQuery('page', 'int', 1));
     $star = new Star();
     $starsItemQuery = $star->getStars($userId);
     $paginator = new \Eva\EvaEngine\Paginator(array("builder" => $starsItemQuery, "limit" => 5, "page" => $query['page']));
     $paginator->setQuery($query);
     $pager = $paginator->getPaginate();
     $this->view->setVar('pager', $pager);
 }
Пример #23
0
 /**
  * Creates a new Comment for the Thread from the submitted data.
  *
  * @param string $uniqueKey The id of the thread
  * @throws \Exception
  */
 public function postThreadCommentsAction($uniqueKey)
 {
     $threadManager = new ThreadManager();
     $thread = $threadManager->findThreadByUniqueKey($uniqueKey);
     if (!$thread) {
         throw new \Exception(sprintf('Thread with identifier of "%s" does not exist', $uniqueKey));
     }
     //        if (!$thread->isCommentable()) {
     //            throw new \Exception(sprintf('Thread "%s" is not commentable', $uniqueKey));
     //        }
     $parentId = $this->request->getPost('parentId');
     $parent = $this->getValidCommentParent($thread, $parentId);
     $content = $this->request->getPost('content');
     $username = $this->request->getPost('username');
     $commentManager = new CommentManager();
     $comment = $commentManager->createComment($thread, $parent);
     //        if ($form->isValid()) {
     $comment->content = $content;
     //        if(!empty($username)) $comment->username = $username;
     $user = new LoginModel();
     if ($user->isUserLoggedIn()) {
         $userinfo = $user->getCurrentUser();
         $comment->userId = $userinfo['id'];
         $comment->username = $userinfo['username'];
     }
     $commentManager->filterContent($comment);
     //政治敏感词过滤
     if ($commentManager->saveComment($comment) !== false) {
         $errors = $comment->getMessages();
         p($errors);
         //                return $this->getViewHandler()->handle($this->onCreateCommentSuccess($form, $id, $parent));
     }
     $this->view->pick('thread/comment');
     $this->view->setVars(array('comment' => $comment, 'thread' => $thread));
 }
Пример #24
0
 public function loginByCookie($tokenString)
 {
     $this->getDI()->getEventsManager()->fire('user:beforeLoginByCookie', $tokenString);
     $tokenArray = explode('|', $tokenString);
     if (!$tokenArray || count($tokenArray) < 3) {
         $this->appendMessage(new Message('ERR_USER_REMEMBER_TOKEN_FORMAT_INCORRECT'));
         return false;
     }
     $token = new Entities\Tokens();
     $token->assign(array('sessionId' => $tokenArray[0], 'token' => $tokenArray[1], 'userHash' => $tokenArray[2]));
     $tokenInfo = $token::findFirst();
     if (!$tokenInfo) {
         $this->appendMessage(new Message('ERR_USER_REMEMBER_TOKEN_NOT_FOUND'));
         return false;
     }
     if ($tokenInfo->expiredAt < time()) {
         $this->appendMessage(new Message('ERR_USER_REMEMBER_TOKEN_EXPIRED'));
         return false;
     }
     $login = new Login();
     $login->id = $tokenInfo->userId;
     return $login->login();
 }
Пример #25
0
 /**
  * @param $mobile
  * @param $captcha
  * @param $userId
  * @return bool
  * @throws Exception\InvalidArgumentException
  * @throws Exception\UnauthorizedException
  */
 public static function bindMobile($mobile, $captcha, $userId)
 {
     /** @var Login $user */
     $user = Login::findFirst('id=' . $userId);
     if (!$user) {
         throw new Exception\UnauthorizedException('ERR_USER_NOT_EXIST');
     }
     if (!$user->mobileCaptchaCheck($mobile, $captcha)) {
         throw new Exception\InvalidArgumentException('ERR_USER_MOBILE_CAPTCHA_CHECK_FAILED');
     }
     $user->mobile = $mobile;
     $user->mobileStatus = 'active';
     $user->mobileConfirmedAt = time();
     $saved = $user->save();
     $user->login();
     return $saved;
 }
Пример #26
0
 public static function logout()
 {
     /** @var \Phalcon\HTTP\ResponseInterface $response */
     $response = IoC::get('response');
     $response->setHeader('P3P', 'CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR');
     $config = IoC::get('config');
     /** @var \Phalcon\Http\Response\Cookies $cookies */
     $cookies = IoC::get('cookies');
     $cookieDomain = $config->session->cookie_params->domain;
     $sso_ticket_name = $config->session->sso_ticket_name;
     $cookies->get(Login::LOGIN_COOKIE_KEY)->setDomain($cookieDomain)->delete();
     $cookies->get(Login::LOGIN_COOKIE_REMEMBER_KEY)->setDomain($cookieDomain)->delete();
     $cookies->get($sso_ticket_name)->setDomain($cookieDomain)->delete();
     Login::getAuthStorage()->remove(Login::AUTH_KEY_LOGIN);
     Login::getAuthStorage()->remove(Login::AUTH_KEY_TOKEN);
     Login::getAuthStorage()->remove(Login::AUTH_KEY_ROLES);
     Login::removeBadges();
 }
Пример #27
0
 public function loginAction()
 {
     if (!$this->request->isPost()) {
         return;
     }
     $user = new OAuthModels\Login();
     if ($this->request->isAjax()) {
         try {
             $user->connectWithPassword($this->request->getPost('identify'), $this->request->getPost('password'), OAuthManager::getAccessToken());
             OAuthManager::removeAccessToken();
             return $this->showResponseAsJson(UserModels\Login::getCurrentUser());
         } catch (\Exception $e) {
             OAuthManager::removeAccessToken();
             return $this->showExceptionAsJson($e, $user->getMessages());
         }
     } else {
         try {
             $accessToken = OAuthManager::getAccessToken();
             $user->connectWithPassword($accessToken);
             OAuthManager::removeAccessToken();
             return $this->redirectHandler($this->getDI()->getConfig()->oauth->loginSuccessRedirectUri);
         } catch (\Exception $e) {
             $this->showException($e, $user->getMessages());
             return $this->redirectHandler($this->getDI()->getConfig()->oauth->loginFailedRedirectUri);
         }
     }
 }
Пример #28
0
 public function checkAction()
 {
     $username = $this->request->get('username');
     $email = $this->request->get('email');
     $mobile = $this->request->get('mobile');
     if ($this->hasQQ($username)) {
         $this->response->setStatusCode('409', 'User Already Exists');
     }
     $loginedUser = Models\Login::getCurrentUser();
     $extraCondition = '';
     // 已登录用户表示当前为修改用户名,允许与当前用户名相同
     if ($loginedUser['id'] > 0) {
         $extraCondition .= ' AND id != ' . $loginedUser['id'];
     }
     if ($username) {
         $userinfo = Models\Login::findFirst(array("username = '******' {$extraCondition}"));
     } elseif ($email) {
         $userinfo = Models\Login::findFirst(array("email = '{$email}' {$extraCondition}"));
     } elseif ($mobile) {
         $userinfo = Models\Login::findFirst(array("mobile = '{$mobile}' {$extraCondition}"));
     } else {
         $userinfo = array();
     }
     $this->view->disable();
     if ($userinfo) {
         $this->response->setStatusCode('409', 'User Already Exists');
     }
     return $this->response->setJsonContent(array('exist' => $userinfo ? true : false, 'id' => $userinfo ? $userinfo->id : 0, 'status' => $userinfo ? $userinfo->status : null));
 }