public function postRegistro() { $input = Input::all(); $reglas = array('nombre' => 'required', 'apellido' => 'required', 'celular' => 'required|numeric|unique:users', 'cedula' => 'required|numeric|unique:users', 'email' => 'required|email|unique:users', 'pin' => 'required|numeric|digits_between:0,4', 'password' => 'required|numbers|case_diff|letters|min:6|confirmed', 'password_confirmation' => 'required|min:6'); $validation = Validator::make($input, $reglas); if ($validation->fails()) { return Response::json(['success' => false, 'errors' => $validation->errors()->toArray()]); } try { // se guarda los datos del usuario $user = Sentry::register(array('first_name' => Input::get('nombre'), 'last_name' => Input::get('apellido'), 'email' => Input::get('email'), 'habilitar_pin' => 1, 'celular' => Input::get('celular'), 'cedula' => Input::get('cedula'), 'password' => Input::get('password'), 'pin' => Input::get('pin'), 'porcentaje' => 0.05, 'activated' => true)); $userId = $user->getId(); $token = new Token(); $token->user_id = $userId; $token->api_token = hash('sha256', Str::random(10), false); $token->client = BrowserDetect::toString(); $token->expires_on = Carbon::now()->addMonth()->toDateTimeString(); $token->save(); // Se autentica de una $user_login = Sentry::findUserById($userId); Sentry::login($user_login, false); return Response::json(['success' => true, 'user' => $user_login, 'token' => $token->api_token]); } catch (Cartalyst\Sentry\Users\LoginRequiredException $e) { $error = array('usuario' => 'Email es requerido'); } catch (Cartalyst\Sentry\Users\PasswordRequiredException $e) { $error = array('usuario' => 'Password es requerido'); } catch (Cartalyst\Sentry\Users\UserExistsException $e) { $error = array('usuario' => 'El Email ya está registrado'); } return Response::json(['success' => false, 'errors' => $error]); }
public static function factory($personId, $function, $expireDate = null) { $token = new Token(); $token->person_id = $personId; $token->token = str_replace('.', '', uniqid('', true)); $token->function = $function; $token->expire_date = $expireDate; $token->save(); return $token; }
/** * Créer un nouveau jeton d'accès * @return Token */ public function getNewToken() { $id = (string) Uuid::uuid4(); $token = new Token(); $token->id = $id; $token->user_id = $this->id; $token->save(); $token->id = $id; return $token; }
/** * Adds a new token to the admin, and returns with the id of the newly created Doctrine model. * * @param object $admin an Admin model object * @param string $tokenType * @param string $token default null if null then one will be generated * @param string $rid default null if null then one will be generated * @return object the new Token model object */ public static function addToken($admin, $tokenType, $token = null, $rid = null) { $model = new Token(); $model->username = $admin['username']; $model->type = $tokenType; $model->token = $token === null ? self::createRandomString() : $token; $model->rid = $rid === null ? self::createRandomString(32) : $rid; $model->save(); return $model; }
public function postIndex() { $input = Input::only('keyword'); $rules = array('keyword' => 'required|min:6'); $v = Validator::make($input, $rules); if ($v->fails()) { return Output::push(array('path' => 'token', 'errors' => $v, 'input' => TRUE)); } $token = new Token(); $token->token = Hash::make($input['keyword']); $token->user_id = Auth::user()->id; $token->save(); return Output::push(array('path' => 'token', 'messages' => array('success' => _('Token was created')))); }
/** * 获得token * @param $userId * @param $orgId * @param $eventId * @return bool 返回false表示生成失败,否则返回sessionId */ protected static function obtainToken($userId, $orgId, $eventId) { session_start(); $sessionId = session_id(); $token = new Token(); $token->expire = time() + self::$expire; $token->create_time = time(); $token->token = $sessionId; $token->event_id = $eventId; $token->user_id = $userId; $token->org_id = $orgId; if (!$token->save()) { return false; } return $sessionId; }
public function actionLogin() { $username = $_POST['username']; $password = $_POST['password']; $identity = new UserIdentity($username, $password); if (!$identity->authenticate()) { Helper::renderJSONErorr("Wrong username or password"); } $token = new Token(); $token->user = $identity->getId(); $token->token = Yii::app()->getSecurityManager()->generateRandomString(64); if ($token->save()) { Helper::renderJSON(["access_token" => $token->token, "token_type" => "bearer"]); } Helper::renderJSONErorr("Internal error"); }
/** * Saves all tokens from session to database * * @param sfEvent $event * @return void */ public static function saveTokenForUser(sfEvent $event) { foreach ($event->getSubject()->getAttributeHolder()->getNamespaces() as $namespace) { if (substr($namespace, 0, 18) == 'sfCacophonyPlugin/') { $t = Doctrine_Core::getTable('Token')->findOneByUserAndProvider($event->getSubject()->getGuardUser(), substr($namespace, 18)); if (!$t) { $t = new Token(); } $me = $event->getSubject()->getAttribute('me', null, $namespace); $t->setProvidersUserId($me['providers_user_id']); $t->setContent($event->getSubject()->getAttribute('accessToken', null, $namespace)); $t->setProvider(substr($namespace, 18)); $t->setUser($event->getSubject()->getGuardUser()); $t->save(); } } }
/** * Account login * @param POST username * @param POST password * @param POST client_secret_uuid * @return object{status, token} */ public function login_post() { $response = new stdClass(); //Parameters check $username = $this->post('username'); $password = $this->post('password'); $client_secret_uuid = $this->post('client_secret_uuid'); if (!empty($username) && !empty($password) && !empty($client_secret_uuid)) { $user = new User(); $user->where('username', $this->post('username'))->where('password', sha1($this->post('password')))->get(); //Record found if ($user->exists()) { $token = uniqid(md5(rand()), true); $token_entry = new Token(); $token_entry->token = $token; $token_entry->user_id = $user->id; //Token expire after 1 year $token_entry->token_expire = time() + 60 * 60 * 24 * 365; $token_entry->client_secret_uuid = $this->post('client_secret_uuid'); if ($token_entry->save()) { $response->status = true; $response->token = $token; } else { $response->status = false; $response->error = "Something wrong in creating Auth Token"; } } else { $response->status = false; $response->error = 'Username / Password wrong'; } } else { $response->status = false; $response->error = 'You must provide username, password and client_secret_uuid'; } $this->response($response); }
public function executeSendPassword(sfWebRequest $request) { // try to find the user by the given E-Mail-Address $user = Doctrine::getTable('User')->findOneByEmail($request->getParameter('email')); if ($user) { // delete all previous recovery tokens Doctrine_Query::create()->delete('Token t')->where('t.user_id=? AND action=?', array($user->getId(), Token::$ACTION_RECOVER))->execute(); // generate recover token $token = new Token(); $token->setUserId($user->getId()); $token->setAction(Token::$ACTION_RECOVER); $token->save(); // sending user email $html = $this->getPartial('recoverEmail', array('user' => $user, 'token' => $token)); $subject = sfContext::getInstance()->getI18N()->__('Your TimeHive password'); MailSender::createInstance()->send($user['email'], $subject, $html); $this->getUser()->setFlash('send_pwd_failure', $this->getContext()->getI18N()->__('An email with instructions to choose a new password has been sent to you.')); $this->redirect('login/index'); } else { $this->getUser()->setFlash('send_pwd_failure', $this->getContext()->getI18N()->__('There is no such e-mail address in the our database!')); $this->redirect('login/index'); } }
function register_post() { $model = json_decode($this->post('models')); $u = new User(); if ($this->_email_existed($model[0]->email)) { $this->response(array('data' => array(), 'metadata' => array('msg' => 'email already used.', 'code' => 500)), 500); } else { $u->username = $model[0]->email; $u->password = $this->_encrypt($model[0]->password); $u->confirm_token = md5(uniqid(mt_rand(), true)); $u->status = 0; if ($u->save()) { $token = new Token(); $token->user_id = $u->id; $token->token = md5(uniqid(mt_rand(), true)); $token->expired = date('Y-m-d', strtotime('+30 days')); $token->save(); $data = array("id" => $u->id, "token" => $token->token, "username" => $u->username, "password" => "hidden", "status" => $u->status === 1 ? true : false, "confirmation" => $u->confirm_token, "companies" => array()); } $this->response(array('user' => $data, 'metadata' => array('msg' => 'user created, waiting for validation.', 'code' => 201)), 201); } }
public static function generatePhoneToken($key, $length) { $token = new Token(); $token->token_key = $key; $token->token_value = rand(pow(10, $length - 1), pow(10, $length) - 1); $token->expiry_date = \Carbon\Carbon::now()->addDay(1); $token->created_at = \Carbon\Carbon::now(); $token->save(); return $token->token_value; }
public static function create($customerId) { $customer = Customer::model()->findByPk($customerId); if ($customer == null) { throw new CHttpException(400, 'Invalid request. Customer id not available.'); } $model = new Token(); $model->token = Yii::app()->hasher->hashPassword(time() . $customer->accountnr); $model->created = time(); $model->customer_id = $customerId; while (!$model->validate()) { $model->token = Yii::app()->hasher->hashPassword(time() . $customer->accountnr); } if ($model->save()) { return $model->token; } return false; }
$selected_bar = Bar::find($_POST['select_bar']); $shopping_cart = null; $displayed_cart = null; return $app['twig']->render("send_token.html.twig", array('user' => $user, 'friend' => $friend, 'friend_bars' => $friend_bars, 'selected_bar' => $selected_bar, 'shopping_cart' => $shopping_cart, 'displayed_cart' => $displayed_cart)); }); //Post Add Token {id}/{friend_id}/{bar_id} $app->post("/add_token/{id}/{friend_id}/{bar_id}", function ($id, $friend_id, $bar_id) use($app) { $user = Patron::find($id); $friend = Patron::find($friend_id); $friend_bars = $friend->getPreferredBars(); $selected_bar = Bar::find($bar_id); $item_id = $_POST['item_id']; $item = Item::find($item_id); $menu_id = $selected_bar->getMenuId($item); $new_token = new Token($friend_id, $menu_id, $id); $new_token->save(); $mail = new PHPMailer(); // $mail->SMTPDebug = 3; $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = '******'; $mail->Password = '******'; $mail->STMPSecure = 'ssl'; $mail->Port = 587; $email_confirmation = $friend->getEmail(); $user_name = $friend->getName(); $mail->From = '*****@*****.**'; $mail->FromName = 'Beer Me!'; $mail->addAddress($email_confirmation, $user_name); $mail->addReplyTo('*****@*****.**', 'Beer Me!');
public function createToken() { $hash = sha1(microtime() . mt_rand() . "salty bastard"); $token = new Token(); $token->set('user_id', $this->id); $token->set('hash', $hash); $token->set('expire_date', date("Y-m-d H:i:s", strtotime("+1 year"))); $token->save(); return $token; }
function testGetTokens() { //Arrange $name = "Kyle Pratuch"; $email = "*****@*****.**"; $test_recipient = new Patron($name, $email); $test_recipient->save(); $name2 = "Jason Bethel"; $email2 = "*****@*****.**"; $test_sender = new Patron($name2, $email2); $test_sender->save(); $bar_name = "Side Street"; $phone = "555-555-5555"; $address = "123 ABC. Street"; $website = "http://www.sidestreetpdx.com"; $test_bar = new Bar($bar_name, $phone, $address, $website); $test_bar->save(); $description = "Pliny the Elder"; $cost = 5.0; $id = null; $test_item = new Item($description, $cost, $id); $test_item->save(); $test_bar->addItem($test_item); $patron_id = $test_recipient->getId(); $sender_id = $test_sender->getId(); $menu_id = 1; $test_token = new Token($patron_id, $menu_id, $sender_id); $test_token->save(); $menu_id2 = 2; $test_token2 = new Token($patron_id, $menu_id2, $sender_id); $test_token2->save(); //Act $result = $test_recipient->getTokens(); //Assert $this->assertEquals([$test_token, $test_token2], $result); }
if (User::where('nickname', 'like', $req_body->nickname)->count()) { $app->halt(400, 'nickname_exists'); } try { $user = new User(); $user->nickname = $req_body->nickname; $user->gender = $req_body->gender; $user->password = sha1($req_body->password1); $user->educationLevel()->associate(EducationLevel::find((int) $req_body->schoolAdvice)); $user->school()->associate(School::find((int) $req_body->school)); $user->save(); // Create token $token = new Token(); $token->generateToken(); $token->user()->associate($user); $token->save(); } catch (Exception $e) { $app->halt(500, 'something_went_wrong'); } echo $token->toJson(); }); $app->get('/user', function () use($app) { $app->response()->header('Content-Type', 'application/json'); $token_key = $app->request->headers->get('Authorization'); try { $user = User::with('talents', 'token')->whereHas('token', function ($q) use($token_key) { $q->where('key', '=', $token_key); })->firstOrFail(); } catch (ModelNotFoundException $e) { $app->halt(401, 'Gebruiker niet gevonden'); }
/** * Generates a login token for the given username * @param string * @return void */ private function generateToken($username) { $user = User::where('username', '=', $username)->first(); $token = new Token(); $token->token = Hash::make($user->username); $token->expiration_date = Carbon::now()->addDay(); $token->user()->associate($user); $token->save(); $user->token()->save($token); $user->save(); }
/** * User Token * * Generates and store the token on behalf of a user */ public function postToken() { if ($this->_isValidRequest()) { $first_name = Input::get('first_name'); $last_name = Input::get('last_name'); $email = Input::get('email'); if (!$first_name or !$last_name or !$email) { $this->_invalidRequest("All parameters are required"); } // Check if token exists or not if ($token = Token::where('email', '=', $email)->first()) { die(json_encode(array("token" => $token->token))); } // Generate new token $timestamp = hash_hmac('sha1', time(), "dksystem"); $unique_token = substr($timestamp, 0, 10) . str_random(22); $token = new Token(); $token->token = $unique_token; $token->first_name = Input::get('first_name'); $token->last_name = Input::get('last_name'); $token->email = Input::get('email'); $token->save(); die(json_encode(array("token" => $unique_token))); } }
/** * Create token for the test * * @param $id */ public function createAction($id) { if (!Auth::user()) { return Redirect::route('admin'); } $test = Test::find($id); if (is_null($test)) { return Redirect::route('info')->with('message', 'Тест не найден'); } $token = new Token(); $token->token = $token->generate($test->name); $token->test_id = $id; $token->save(); return View::make('test.token', ['token' => $token->token]); }
// return generate randome token $token_expiration = date('Y-m-d H:i:s', strtotime('+1 hour')); // the expiration date will be in one hour from the current moment // update token into database // this methode will cause logout state in other device // because the token not valid again $token = Token::find_by_user_id($users->user_id); if ($token) { // update token $token->token = $token_expiration; $token->save(); // write log $this->logger->info("Slim-Api '/' login"); return $response->getBody()->write(json_encode($res)); } else { // insert token $post = new Token(); $post->token = $res['token']; $post->user_id = $users->user_id; $post->expire = $token_expiration; $post->save(); // insert into database // write log $this->logger->info("Slim-Api '/' login"); // trow response json return $response->getBody()->write(json_encode($res)); } } else { return $response->getBody()->write(json_encode(false)); } });
public function actionCreateToken($cust_id) { if (Yii::app()->request->isAjaxRequest) { if (isset($cust_id)) { $customer = Customer::model()->findByPk($cust_id); $new_token = new Token(); $new_token->customer_id = $customer->id; $new_token->token = Token::create($customer->id); $new_token->created = time(); $new_token->save(); $criteria = new CDbCriteria(); $criteria->condition = 'customer_id=' . $customer->id; $customer_tokens = new CActiveDataProvider('Token', array('criteria' => $criteria)); $this->renderPartial('_tokens', array('customer_tokens' => $customer_tokens)); } } }
function loginUser() { $data = Functions::getJSONData(); $nickname = Functions::elt($data, 'nickname'); $password = Functions::elt($data, 'password'); $expiration = Functions::elt($data, 'expiration'); $actionCount = Functions::elt($data, 'actionCount'); if (is_null($nickname) || is_null($password) || is_null($expiration) || is_null($actionCount)) { Functions::setResponse(400); } $whereClause = 'nickname = :nickname'; $params = array(array('id' => ':nickname', 'value' => $nickname)); $custList = Customer::search($whereClause, $params); if (!count($custList)) { Functions::setResponse(403); } $customer = $custList[0]; if (Functions::hash($password) == $customer->get('password')) { $t = new Token(); $t->set('customerId', $customer->get('id')); $t->set('value', Functions::randomHash()); $t->set('expiration', time() + floor($expiration / 1000)); $t->set('actionCount', $actionCount); $t->save(); return $t; } else { Functions::setResponse(403); } }
public function login($id) { $user = User::where('username', '=', $id)->firstOrFail(); if (Hash::check(Input::get('password'), $user->password)) { if (!is_null($user->token)) { $user->token->delete(); } $token = new Token(); $token->token = Hash::make($user->username); $token->expiration_date = Carbon::now()->addDay(); $token->user()->associate($user); $token->save(); $user->token()->save($token); $user->save(); return Response::json(array('token' => $token->token), 200); } else { return Response::json(array('message' => 'invalid password!'), 401); } }
function testDelete() { $patron_id = 1; $menu_id = 2; $sender_id = 3; $test_token = new Token($patron_id, $menu_id, $sender_id); $test_token->save(); $patron_id2 = 4; $menu_id2 = 5; $sender_id2 = 6; $test_token2 = new Token($patron_id2, $menu_id2, $sender_id2); $test_token2->save(); $test_token->delete(); $result = Token::getAll(); $this->assertEquals([$test_token2], $result); }
function testGetAllTokens() { $name = "Side Street"; $phone = "555-555-5555"; $address = "123 ABC. Street"; $website = "http://www.sidestreetpdx.com"; $test_bar = new Bar($name, $phone, $address, $website); $test_bar->save(); $test_item = new Item("tacos", 2.25); $test_item->save(); $test_bar->addItem($test_item); $returned_ids = $GLOBALS['DB']->query("SELECT id FROM menus WHERE bar_id = {$test_bar->getId()};"); $ids = array(); foreach ($returned_ids as $returned_id) { $id = $returned_id['id']; array_push($ids, $id); } $name = "Kyle Pratuch"; $email = "*****@*****.**"; $test_patron = new Patron($name, $email); $test_patron->save(); $test_token = new Token($test_patron->getId(), $ids[0], 3); $test_token->save(); // var_dump($test_token); $result = $test_bar->getAllTokens(); $this->assertEquals($test_token, $result[0]); }