{"_id":"57af563ece173c20004b8e26","parentDoc":null,"title":"What is UserKit?","createdAt":"2016-08-13T17:17:50.798Z","githubsync":"","hidden":false,"isReference":false,"link_external":false,"order":0,"api":{"auth":"required","params":[],"url":"","results":{"codes":[]},"settings":""},"body":"UserKit lets you add user login, registration and account management to your website or app, all in under 10 minutes.\n\nUserKit handles your user's account life-cycle for you, including:\n\n - Signup\n - Login\n - Password reset\n - Account settings (users can change their email, enable 2-factor login, etc.)\n - Invites\n - [Dashboard](https://dashboard.userkit.io) to view and manage your app's users\n\nWith all that taken care of, you can focus on building your product.","updates":[],"user":"5542d87d795b590d001dc7ff","version":"5589ceae9883a40d00c433f6","__v":0,"link_url":"","project":"5589ceae9883a40d00c433f3","slug":"what-is-userkit","sync_unique":"","type":"basic","category":"559ab19d2100d117005f1269","excerpt":"","childrenPages":[]}

What is UserKit?


UserKit lets you add user login, registration and account management to your website or app, all in under 10 minutes. UserKit handles your user's account life-cycle for you, including: - Signup - Login - Password reset - Account settings (users can change their email, enable 2-factor login, etc.) - Invites - [Dashboard](https://dashboard.userkit.io) to view and manage your app's users With all that taken care of, you can focus on building your product.
UserKit lets you add user login, registration and account management to your website or app, all in under 10 minutes. UserKit handles your user's account life-cycle for you, including: - Signup - Login - Password reset - Account settings (users can change their email, enable 2-factor login, etc.) - Invites - [Dashboard](https://dashboard.userkit.io) to view and manage your app's users With all that taken care of, you can focus on building your product.
{"_id":"57acad697ae5c60e004ba3c4","excerpt":"Add login and user account management to your website in a few easy steps.","hidden":false,"sync_unique":"","user":"5542d87d795b590d001dc7ff","body":"Add the UserKit widget for login and registration to your webpage, and then check on the server if a user is logged in.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"1. Create your UserKit app\"\n}\n[/block]\nSign into the <a href=\"https://dashboard.userkit.io\" target=\"_blank\">dashboard</a> and create a UserKit app.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"2. Create an account page\"\n}\n[/block]\nCreate a folder named *quickstart*, and in that folder create a file named *account.html* containing the UserKit widget. Replace `\"<YOUR_USERKIT_APP_ID>\"` with your UserKit app id.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<html>\\n  <head></head>\\n  <body>\\n   \\t\\n    <script src=\\\"https://widget.userkit.io/widget.js\\\"\\n    \\tdata-app-id=\\\"<YOUR_USERKIT_APP_ID>\\\"\\n      data-show-on-load=\\\"auto\\\">\\n    </script>\\n    \\n  </body>\\n</html>\",\n      \"language\": \"html\",\n      \"name\": \"account.html\"\n    }\n  ]\n}\n[/block]\nThe ```<script>``` tag inserts the UserKit widget into the page. When you load this page in a web browser you should now see the widget. See below for an example of what you should now see on your page.\n[block:embed]\n{\n  \"html\": \"<iframe height='350' scrolling='no' src='https://codepen.io/userkit/embed/BQvZxV' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'></iframe>\",\n  \"url\": \"https://codepen.io/userkit/pen/BQvZxV\",\n  \"title\": \"BQvZxV\",\n  \"favicon\": \"https://production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico\",\n  \"image\": \"https://s3-us-west-2.amazonaws.com/i.cdpn.io/978639.BQvZxV.small.9dbe21e9-3cb6-451d-b4b0-2accde26d5c2.png\"\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"You'll need to serve *account.html* from a server for the widget to work properly, since some browsers don't allow cookies otherwise. On any computer that has Python installed (it's preinstalled on Mac and Linux) you can run the following command from the *quickstart* directory in your terminal:\\n\\n```\\npython -m SimpleHTTPServer 8080\\n```\\n\\nThen, in your web browser go to http://localhost:8080/account.html to view the page.\",\n  \"title\": \"\"\n}\n[/block]\nFor visitors who aren't logged in, the widget will display a login form. If a visitor is logged in, the widget will display the account settings form instead where that user can change their name, email or other account settings. See <a href=\"https://docs.userkit.io/docs/widget-configuration\">UserKitWidget Configuration</a> documentation for more details\n\nWhen a user is logged in, the widget will set a cookie named `userkit_auth_token` containing a user-session token. You'll use this token to fetch a logged-in user in step 3.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"3. Check if a user is logged in\"\n}\n[/block]\nYour server can now check if there is a logged in user associated with a request. It does this by using the user-session token stored in the `userkit_auth_token` cookie to fetch the user from the UserKit API.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"import userkit\\n\\nuk = userkit.UserKit(\\\"<YOUR_APP_SECRET_KEY>\\\")\\n\\n\\ndef request_handler(request, response):\\n  token = request.get_cookie(\\\"userkit_auth_token\\\")\\n  user = uk.users.get_current_user(token)\\n  \\n  if user:\\n    # There's a logged in user\\n    response.write(\\\"Welcome, {}\\\".format(user.name))\\n  else:\\n    # No logged in user, redirect to login page\\n    response.redirect(\\\"/account.html\\\")\\n\",\n      \"language\": \"python\"\n    },\n    {\n      \"code\": \"require 'json'\\nrequire 'rest-client'\\n\\ndef get_current_user(session_token)\\n  resource = RestClient::Resource.new(\\n    'https://api.userkit.io/v1/users/by_token',\\n    'api', '<YOUR_APP_SECRET_KEY>')\\n  begin\\n \\t\\tresponse = resource.get(:'X-User-TOken' => session_token)\\n    return JSON.parse(response.body)\\n \\trescue RestClient::Exception\\n  \\treturn nil\\n  end\\nend\\n\\n\\ndef request_handler(request, response)\\n  token = request.get_cookie(\\\"userkit_auth_token\\\")\\n  user = get_current_user(token)\\n  \\n  if (user)\\n    # There's a logged in user\\n    response.write(\\\"Welcome, \\\" + user.name)\\n  else\\n    # No logged in user, redirect to login page\\n    response.redirect(\\\"/account.html\\\")\\n  end\\nend\\n\",\n      \"language\": \"ruby\",\n      \"name\": \"Ruby\"\n    },\n    {\n      \"code\": \"package example\\n\\nimport (\\n\\t\\\"fmt\\\"\\n  userkit \\\"github.com/workpail/userkit-go\\\"\\n)\\n\\nfunc HandleSomeRequest(w http.ResponseWriter, r *http.Request) {\\n  uk := userkit.NewUserKit(\\\"<YOUR_APP_SECRET_KEY>\\\")\\n  \\n\\ttokenCookie, _ := r.Cookie(\\\"userkit_auth_token\\\")\\n\\tuser, err := uk.Users.GetUserBySession(tokenCookie.Value)\\n\\tif err != nil {\\n\\t\\t// No logged in user, redirect to login page\\n\\t\\thttp.Redirect(w, r, \\\"/account.html\\\", 401)\\n\\t\\treturn\\n\\t}\\n\\n\\t// There's a logged in user\\n\\tw.Write([]byte(\\\"Welcome, \\\" + user.Name))\\n}\",\n      \"language\": \"go\",\n      \"name\": \"Go\"\n    },\n    {\n      \"code\": \"<?php\\n\\nrequire_once('UserKit.php');\\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\\n\\nfunction request_handler($request, $response)\\n{\\n  global $uk;\\n\\n  $token = $request->get_cookie('userkit_auth_token');\\n  $user = $uk->users->getCurrentUser($token);\\n  if ($user != null)\\n  {\\n    // There's a logged in user\\n    $response->write(\\\"Welcome, $user->name\\\");\\n  }\\n  else\\n  {\\n    // No logged in user, redirect to login page\\n    $response->redirect('/account.html');\\n  }\\n}\\n\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"4. Add Buttons for Login, Account Settings, Registration and Logout\"\n}\n[/block]\nThe UserKit widget can also be configured to remain hidden on load by omitting the `data-show-on-load` property. You can add your own javascript to display a specific widget page such as login, settings, or registration on the click event of a button or link, or to logout the user.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<!-- Omit the data-show-on-load property so widget remains hidden -->\\n<script src=\\\"https://widget.userkit.io/widget.js\\\"\\n\\tdata-app-id=\\\"<YOUR_USERKIT_APP_ID>\\\">\\n</script>\\n\\n\\n<!-- Login button -->\\n<button onclick=\\\"UserKitWidget.open('login')\\\">Login</button>\\n\\n<!-- Signup button -->\\n<button onclick=\\\"UserKitWidget.open('register')\\\">Register</button>\\n\\n<!-- Account settings button -->\\n<button onclick=\\\"UserKitWidget.open('settings')\\\">Account Settings</button>\\n\\n<!-- Logout button -->\\n<button onclick=\\\"UserKit.logout()\\\">Logout</button>\\n\",\n      \"language\": \"javascript\",\n      \"name\": \"HTML\"\n    }\n  ]\n}\n[/block]\n\n[block:embed]\n{\n  \"html\": \"<iframe height='350' scrolling='no' src='https://codepen.io/userkit/embed/yVGzKK' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'></iframe>\",\n  \"url\": \"https://codepen.io/userkit/pen/yVGzKK\",\n  \"title\": \"yVGzKK\",\n  \"favicon\": \"https://production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico\",\n  \"image\": \"http://codepen.io/userkit/pen/yVGzKK/image/large.png\"\n}\n[/block]\nTo learn more about what functions are available within the widget, see the widget <a href=\"https://docs.userkit.io/docs/javascript-api\">Javascript API</a> documentation.","createdAt":"2016-08-11T16:52:57.987Z","githubsync":"","isReference":true,"link_external":false,"link_url":"","next":{"description":"","pages":[]},"slug":"quickstart","__v":1,"api":{"settings":"","auth":"required","params":[],"url":"","results":{"codes":[{"status":200,"language":"json","code":"{}","name":""},{"status":400,"language":"json","code":"{}","name":""}]}},"title":"Quickstart","order":1,"parentDoc":null,"project":"5589ceae9883a40d00c433f3","type":"basic","updates":[],"version":"5589ceae9883a40d00c433f6","category":"559ab19d2100d117005f1269","childrenPages":[]}

Quickstart

Add login and user account management to your website in a few easy steps.

Add the UserKit widget for login and registration to your webpage, and then check on the server if a user is logged in. [block:api-header] { "type": "basic", "title": "1. Create your UserKit app" } [/block] Sign into the <a href="https://dashboard.userkit.io" target="_blank">dashboard</a> and create a UserKit app. [block:api-header] { "type": "basic", "title": "2. Create an account page" } [/block] Create a folder named *quickstart*, and in that folder create a file named *account.html* containing the UserKit widget. Replace `"<YOUR_USERKIT_APP_ID>"` with your UserKit app id. [block:code] { "codes": [ { "code": "<html>\n <head></head>\n <body>\n \t\n <script src=\"https://widget.userkit.io/widget.js\"\n \tdata-app-id=\"<YOUR_USERKIT_APP_ID>\"\n data-show-on-load=\"auto\">\n </script>\n \n </body>\n</html>", "language": "html", "name": "account.html" } ] } [/block] The ```<script>``` tag inserts the UserKit widget into the page. When you load this page in a web browser you should now see the widget. See below for an example of what you should now see on your page. [block:embed] { "html": "<iframe height='350' scrolling='no' src='https://codepen.io/userkit/embed/BQvZxV' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'></iframe>", "url": "https://codepen.io/userkit/pen/BQvZxV", "title": "BQvZxV", "favicon": "https://production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico", "image": "https://s3-us-west-2.amazonaws.com/i.cdpn.io/978639.BQvZxV.small.9dbe21e9-3cb6-451d-b4b0-2accde26d5c2.png" } [/block] [block:callout] { "type": "info", "body": "You'll need to serve *account.html* from a server for the widget to work properly, since some browsers don't allow cookies otherwise. On any computer that has Python installed (it's preinstalled on Mac and Linux) you can run the following command from the *quickstart* directory in your terminal:\n\n```\npython -m SimpleHTTPServer 8080\n```\n\nThen, in your web browser go to http://localhost:8080/account.html to view the page.", "title": "" } [/block] For visitors who aren't logged in, the widget will display a login form. If a visitor is logged in, the widget will display the account settings form instead where that user can change their name, email or other account settings. See <a href="https://docs.userkit.io/docs/widget-configuration">UserKitWidget Configuration</a> documentation for more details When a user is logged in, the widget will set a cookie named `userkit_auth_token` containing a user-session token. You'll use this token to fetch a logged-in user in step 3. [block:api-header] { "type": "basic", "title": "3. Check if a user is logged in" } [/block] Your server can now check if there is a logged in user associated with a request. It does this by using the user-session token stored in the `userkit_auth_token` cookie to fetch the user from the UserKit API. [block:code] { "codes": [ { "code": "import userkit\n\nuk = userkit.UserKit(\"<YOUR_APP_SECRET_KEY>\")\n\n\ndef request_handler(request, response):\n token = request.get_cookie(\"userkit_auth_token\")\n user = uk.users.get_current_user(token)\n \n if user:\n # There's a logged in user\n response.write(\"Welcome, {}\".format(user.name))\n else:\n # No logged in user, redirect to login page\n response.redirect(\"/account.html\")\n", "language": "python" }, { "code": "require 'json'\nrequire 'rest-client'\n\ndef get_current_user(session_token)\n resource = RestClient::Resource.new(\n 'https://api.userkit.io/v1/users/by_token',\n 'api', '<YOUR_APP_SECRET_KEY>')\n begin\n \t\tresponse = resource.get(:'X-User-TOken' => session_token)\n return JSON.parse(response.body)\n \trescue RestClient::Exception\n \treturn nil\n end\nend\n\n\ndef request_handler(request, response)\n token = request.get_cookie(\"userkit_auth_token\")\n user = get_current_user(token)\n \n if (user)\n # There's a logged in user\n response.write(\"Welcome, \" + user.name)\n else\n # No logged in user, redirect to login page\n response.redirect(\"/account.html\")\n end\nend\n", "language": "ruby", "name": "Ruby" }, { "code": "package example\n\nimport (\n\t\"fmt\"\n userkit \"github.com/workpail/userkit-go\"\n)\n\nfunc HandleSomeRequest(w http.ResponseWriter, r *http.Request) {\n uk := userkit.NewUserKit(\"<YOUR_APP_SECRET_KEY>\")\n \n\ttokenCookie, _ := r.Cookie(\"userkit_auth_token\")\n\tuser, err := uk.Users.GetUserBySession(tokenCookie.Value)\n\tif err != nil {\n\t\t// No logged in user, redirect to login page\n\t\thttp.Redirect(w, r, \"/account.html\", 401)\n\t\treturn\n\t}\n\n\t// There's a logged in user\n\tw.Write([]byte(\"Welcome, \" + user.Name))\n}", "language": "go", "name": "Go" }, { "code": "<?php\n\nrequire_once('UserKit.php');\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\nfunction request_handler($request, $response)\n{\n global $uk;\n\n $token = $request->get_cookie('userkit_auth_token');\n $user = $uk->users->getCurrentUser($token);\n if ($user != null)\n {\n // There's a logged in user\n $response->write(\"Welcome, $user->name\");\n }\n else\n {\n // No logged in user, redirect to login page\n $response->redirect('/account.html');\n }\n}\n", "language": "php" } ] } [/block] [block:api-header] { "type": "basic", "title": "4. Add Buttons for Login, Account Settings, Registration and Logout" } [/block] The UserKit widget can also be configured to remain hidden on load by omitting the `data-show-on-load` property. You can add your own javascript to display a specific widget page such as login, settings, or registration on the click event of a button or link, or to logout the user. [block:code] { "codes": [ { "code": "<!-- Omit the data-show-on-load property so widget remains hidden -->\n<script src=\"https://widget.userkit.io/widget.js\"\n\tdata-app-id=\"<YOUR_USERKIT_APP_ID>\">\n</script>\n\n\n<!-- Login button -->\n<button onclick=\"UserKitWidget.open('login')\">Login</button>\n\n<!-- Signup button -->\n<button onclick=\"UserKitWidget.open('register')\">Register</button>\n\n<!-- Account settings button -->\n<button onclick=\"UserKitWidget.open('settings')\">Account Settings</button>\n\n<!-- Logout button -->\n<button onclick=\"UserKit.logout()\">Logout</button>\n", "language": "javascript", "name": "HTML" } ] } [/block] [block:embed] { "html": "<iframe height='350' scrolling='no' src='https://codepen.io/userkit/embed/yVGzKK' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'></iframe>", "url": "https://codepen.io/userkit/pen/yVGzKK", "title": "yVGzKK", "favicon": "https://production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico", "image": "http://codepen.io/userkit/pen/yVGzKK/image/large.png" } [/block] To learn more about what functions are available within the widget, see the widget <a href="https://docs.userkit.io/docs/javascript-api">Javascript API</a> documentation.
Add the UserKit widget for login and registration to your webpage, and then check on the server if a user is logged in. [block:api-header] { "type": "basic", "title": "1. Create your UserKit app" } [/block] Sign into the <a href="https://dashboard.userkit.io" target="_blank">dashboard</a> and create a UserKit app. [block:api-header] { "type": "basic", "title": "2. Create an account page" } [/block] Create a folder named *quickstart*, and in that folder create a file named *account.html* containing the UserKit widget. Replace `"<YOUR_USERKIT_APP_ID>"` with your UserKit app id. [block:code] { "codes": [ { "code": "<html>\n <head></head>\n <body>\n \t\n <script src=\"https://widget.userkit.io/widget.js\"\n \tdata-app-id=\"<YOUR_USERKIT_APP_ID>\"\n data-show-on-load=\"auto\">\n </script>\n \n </body>\n</html>", "language": "html", "name": "account.html" } ] } [/block] The ```<script>``` tag inserts the UserKit widget into the page. When you load this page in a web browser you should now see the widget. See below for an example of what you should now see on your page. [block:embed] { "html": "<iframe height='350' scrolling='no' src='https://codepen.io/userkit/embed/BQvZxV' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'></iframe>", "url": "https://codepen.io/userkit/pen/BQvZxV", "title": "BQvZxV", "favicon": "https://production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico", "image": "https://s3-us-west-2.amazonaws.com/i.cdpn.io/978639.BQvZxV.small.9dbe21e9-3cb6-451d-b4b0-2accde26d5c2.png" } [/block] [block:callout] { "type": "info", "body": "You'll need to serve *account.html* from a server for the widget to work properly, since some browsers don't allow cookies otherwise. On any computer that has Python installed (it's preinstalled on Mac and Linux) you can run the following command from the *quickstart* directory in your terminal:\n\n```\npython -m SimpleHTTPServer 8080\n```\n\nThen, in your web browser go to http://localhost:8080/account.html to view the page.", "title": "" } [/block] For visitors who aren't logged in, the widget will display a login form. If a visitor is logged in, the widget will display the account settings form instead where that user can change their name, email or other account settings. See <a href="https://docs.userkit.io/docs/widget-configuration">UserKitWidget Configuration</a> documentation for more details When a user is logged in, the widget will set a cookie named `userkit_auth_token` containing a user-session token. You'll use this token to fetch a logged-in user in step 3. [block:api-header] { "type": "basic", "title": "3. Check if a user is logged in" } [/block] Your server can now check if there is a logged in user associated with a request. It does this by using the user-session token stored in the `userkit_auth_token` cookie to fetch the user from the UserKit API. [block:code] { "codes": [ { "code": "import userkit\n\nuk = userkit.UserKit(\"<YOUR_APP_SECRET_KEY>\")\n\n\ndef request_handler(request, response):\n token = request.get_cookie(\"userkit_auth_token\")\n user = uk.users.get_current_user(token)\n \n if user:\n # There's a logged in user\n response.write(\"Welcome, {}\".format(user.name))\n else:\n # No logged in user, redirect to login page\n response.redirect(\"/account.html\")\n", "language": "python" }, { "code": "require 'json'\nrequire 'rest-client'\n\ndef get_current_user(session_token)\n resource = RestClient::Resource.new(\n 'https://api.userkit.io/v1/users/by_token',\n 'api', '<YOUR_APP_SECRET_KEY>')\n begin\n \t\tresponse = resource.get(:'X-User-TOken' => session_token)\n return JSON.parse(response.body)\n \trescue RestClient::Exception\n \treturn nil\n end\nend\n\n\ndef request_handler(request, response)\n token = request.get_cookie(\"userkit_auth_token\")\n user = get_current_user(token)\n \n if (user)\n # There's a logged in user\n response.write(\"Welcome, \" + user.name)\n else\n # No logged in user, redirect to login page\n response.redirect(\"/account.html\")\n end\nend\n", "language": "ruby", "name": "Ruby" }, { "code": "package example\n\nimport (\n\t\"fmt\"\n userkit \"github.com/workpail/userkit-go\"\n)\n\nfunc HandleSomeRequest(w http.ResponseWriter, r *http.Request) {\n uk := userkit.NewUserKit(\"<YOUR_APP_SECRET_KEY>\")\n \n\ttokenCookie, _ := r.Cookie(\"userkit_auth_token\")\n\tuser, err := uk.Users.GetUserBySession(tokenCookie.Value)\n\tif err != nil {\n\t\t// No logged in user, redirect to login page\n\t\thttp.Redirect(w, r, \"/account.html\", 401)\n\t\treturn\n\t}\n\n\t// There's a logged in user\n\tw.Write([]byte(\"Welcome, \" + user.Name))\n}", "language": "go", "name": "Go" }, { "code": "<?php\n\nrequire_once('UserKit.php');\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\nfunction request_handler($request, $response)\n{\n global $uk;\n\n $token = $request->get_cookie('userkit_auth_token');\n $user = $uk->users->getCurrentUser($token);\n if ($user != null)\n {\n // There's a logged in user\n $response->write(\"Welcome, $user->name\");\n }\n else\n {\n // No logged in user, redirect to login page\n $response->redirect('/account.html');\n }\n}\n", "language": "php" } ] } [/block] [block:api-header] { "type": "basic", "title": "4. Add Buttons for Login, Account Settings, Registration and Logout" } [/block] The UserKit widget can also be configured to remain hidden on load by omitting the `data-show-on-load` property. You can add your own javascript to display a specific widget page such as login, settings, or registration on the click event of a button or link, or to logout the user. [block:code] { "codes": [ { "code": "<!-- Omit the data-show-on-load property so widget remains hidden -->\n<script src=\"https://widget.userkit.io/widget.js\"\n\tdata-app-id=\"<YOUR_USERKIT_APP_ID>\">\n</script>\n\n\n<!-- Login button -->\n<button onclick=\"UserKitWidget.open('login')\">Login</button>\n\n<!-- Signup button -->\n<button onclick=\"UserKitWidget.open('register')\">Register</button>\n\n<!-- Account settings button -->\n<button onclick=\"UserKitWidget.open('settings')\">Account Settings</button>\n\n<!-- Logout button -->\n<button onclick=\"UserKit.logout()\">Logout</button>\n", "language": "javascript", "name": "HTML" } ] } [/block] [block:embed] { "html": "<iframe height='350' scrolling='no' src='https://codepen.io/userkit/embed/yVGzKK' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'></iframe>", "url": "https://codepen.io/userkit/pen/yVGzKK", "title": "yVGzKK", "favicon": "https://production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico", "image": "http://codepen.io/userkit/pen/yVGzKK/image/large.png" } [/block] To learn more about what functions are available within the widget, see the widget <a href="https://docs.userkit.io/docs/javascript-api">Javascript API</a> documentation.
{"_id":"584710030e16da1900b283b7","hidden":false,"link_external":false,"type":"basic","createdAt":"2016-12-06T19:22:43.549Z","excerpt":"","githubsync":"","link_url":"","project":"5589ceae9883a40d00c433f3","body":"The following data properties are available for configuring the UserKit Widget.\n\n- `data-app-id` (Required)\nThis property is required and must be set to the app-id for your app found in the [UserKit Dashboard](https://dashboard.userkit.io)\n\n- `data-show-on-load` (Optional, Default = `undefined`)\nMay be set to `login`, `register`, `settings`, or `auto`. This property will display the dialog for the selected value on page load. The `auto` setting will display the `login` page for users who are not logged in and the `settings` page for users who are logged in.\n\n- `data-login-dismiss` (Optional, Default = `true`)\nSetting this property to false will prevent the `login` dialog from being dismissed.\n\n- `data-register-dismiss` (Optional, Default = `true`)\nSetting this property to false will prevent the `register` dialog from being dismissed.\n\n- `data-settings-dismiss` (Optional, Default = `true`)\nSetting this property to false will prevent the `settings` dialog from being dismissed.\n\n- `data-proxy` (Optional, Default = `undefined`)\nCan be used to enable http-only session cookies. More info [here](https://docs.userkit.io/docs/overview-http-only-cookies)","category":"5846c4ee5d064323007b1774","slug":"widget-configuration","title":"Configuration options","updates":[],"user":"555297897e64980d008d3baf","__v":0,"parentDoc":null,"isReference":false,"next":{"pages":[],"description":""},"order":1,"sync_unique":"","version":"5589ceae9883a40d00c433f6","api":{"params":[],"url":"","results":{"codes":[{"status":200,"language":"json","code":"{}","name":""},{"status":400,"language":"json","code":"{}","name":""}]},"settings":"","auth":"required"},"childrenPages":[]}

Configuration options


The following data properties are available for configuring the UserKit Widget. - `data-app-id` (Required) This property is required and must be set to the app-id for your app found in the [UserKit Dashboard](https://dashboard.userkit.io) - `data-show-on-load` (Optional, Default = `undefined`) May be set to `login`, `register`, `settings`, or `auto`. This property will display the dialog for the selected value on page load. The `auto` setting will display the `login` page for users who are not logged in and the `settings` page for users who are logged in. - `data-login-dismiss` (Optional, Default = `true`) Setting this property to false will prevent the `login` dialog from being dismissed. - `data-register-dismiss` (Optional, Default = `true`) Setting this property to false will prevent the `register` dialog from being dismissed. - `data-settings-dismiss` (Optional, Default = `true`) Setting this property to false will prevent the `settings` dialog from being dismissed. - `data-proxy` (Optional, Default = `undefined`) Can be used to enable http-only session cookies. More info [here](https://docs.userkit.io/docs/overview-http-only-cookies)
The following data properties are available for configuring the UserKit Widget. - `data-app-id` (Required) This property is required and must be set to the app-id for your app found in the [UserKit Dashboard](https://dashboard.userkit.io) - `data-show-on-load` (Optional, Default = `undefined`) May be set to `login`, `register`, `settings`, or `auto`. This property will display the dialog for the selected value on page load. The `auto` setting will display the `login` page for users who are not logged in and the `settings` page for users who are logged in. - `data-login-dismiss` (Optional, Default = `true`) Setting this property to false will prevent the `login` dialog from being dismissed. - `data-register-dismiss` (Optional, Default = `true`) Setting this property to false will prevent the `register` dialog from being dismissed. - `data-settings-dismiss` (Optional, Default = `true`) Setting this property to false will prevent the `settings` dialog from being dismissed. - `data-proxy` (Optional, Default = `undefined`) Can be used to enable http-only session cookies. More info [here](https://docs.userkit.io/docs/overview-http-only-cookies)
{"_id":"58471465889b6c2d00fb8583","isReference":false,"order":2,"parentDoc":null,"title":"Javascript API","updates":[],"api":{"results":{"codes":[{"code":"{}","name":"","status":200,"language":"json"},{"name":"","status":400,"language":"json","code":"{}"}]},"settings":"","auth":"required","params":[],"url":""},"body":"Open a particular dialog\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"UserKitWidget.open(dialog);\",\n      \"language\": \"javascript\",\n      \"name\": \"UserKitWidget.open(dialog)\"\n    }\n  ]\n}\n[/block]\nIf the dialog you are attempting to open requires a login, the user will be prompted to login first.\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Page ID\",\n    \"h-1\": \"Description\",\n    \"h-2\": \"Login Required?\",\n    \"0-0\": \"change_password\",\n    \"1-0\": \"forgot_password\",\n    \"2-0\": \"login\",\n    \"3-0\": \"register\",\n    \"4-0\": \"settings\",\n    \"5-0\": \"request_phone_verification_code\",\n    \"6-0\": \"\",\n    \"0-1\": \"Provides a form allowing users to change their current password\",\n    \"0-2\": \"Yes\",\n    \"1-1\": \"Prompts the user to enter the identifier used to login. They will receive an email with instructions to reset their password.\",\n    \"1-2\": \"No\",\n    \"2-2\": \"No\",\n    \"2-1\": \"Login form\",\n    \"3-1\": \"User registration form\",\n    \"3-2\": \"No\",\n    \"4-1\": \"Displays a form with the options for the current user to manage their user information\",\n    \"4-2\": \"Yes\",\n    \"5-1\": \"Used to validate phone numbers and change how a user logs in\",\n    \"5-2\": \"No\"\n  },\n  \"cols\": 3,\n  \"rows\": 6\n}\n[/block]\nClose all open dialogs\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"UserKitWidget.dismiss();\",\n      \"language\": \"text\",\n      \"name\": \"UserKitWidget.dismiss();\"\n    }\n  ]\n}\n[/block]\nLogout current user\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"UserKit.logout();\",\n      \"language\": \"javascript\",\n      \"name\": \"UserKit.logout()\"\n    }\n  ]\n}\n[/block]\nGet current user data\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"UserKit.getUser();\",\n      \"language\": \"text\",\n      \"name\": \"UserKit.getUser()\"\n    }\n  ]\n}\n[/block]\nCheck if user is currently logged in\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"UserKit.isLoggedIn();\",\n      \"language\": \"text\",\n      \"name\": \"UserKit.isLoggedIn()\"\n    }\n  ]\n}\n[/block]","category":"5846c4ee5d064323007b1774","type":"basic","version":"5589ceae9883a40d00c433f6","__v":0,"excerpt":"","link_url":"","user":"555297897e64980d008d3baf","createdAt":"2016-12-06T19:41:25.213Z","link_external":false,"slug":"javascript-api","next":{"pages":[],"description":""},"project":"5589ceae9883a40d00c433f3","sync_unique":"","githubsync":"","hidden":false,"childrenPages":[]}

Javascript API


Open a particular dialog [block:code] { "codes": [ { "code": "UserKitWidget.open(dialog);", "language": "javascript", "name": "UserKitWidget.open(dialog)" } ] } [/block] If the dialog you are attempting to open requires a login, the user will be prompted to login first. [block:parameters] { "data": { "h-0": "Page ID", "h-1": "Description", "h-2": "Login Required?", "0-0": "change_password", "1-0": "forgot_password", "2-0": "login", "3-0": "register", "4-0": "settings", "5-0": "request_phone_verification_code", "6-0": "", "0-1": "Provides a form allowing users to change their current password", "0-2": "Yes", "1-1": "Prompts the user to enter the identifier used to login. They will receive an email with instructions to reset their password.", "1-2": "No", "2-2": "No", "2-1": "Login form", "3-1": "User registration form", "3-2": "No", "4-1": "Displays a form with the options for the current user to manage their user information", "4-2": "Yes", "5-1": "Used to validate phone numbers and change how a user logs in", "5-2": "No" }, "cols": 3, "rows": 6 } [/block] Close all open dialogs [block:code] { "codes": [ { "code": "UserKitWidget.dismiss();", "language": "text", "name": "UserKitWidget.dismiss();" } ] } [/block] Logout current user [block:code] { "codes": [ { "code": "UserKit.logout();", "language": "javascript", "name": "UserKit.logout()" } ] } [/block] Get current user data [block:code] { "codes": [ { "code": "UserKit.getUser();", "language": "text", "name": "UserKit.getUser()" } ] } [/block] Check if user is currently logged in [block:code] { "codes": [ { "code": "UserKit.isLoggedIn();", "language": "text", "name": "UserKit.isLoggedIn()" } ] } [/block]
Open a particular dialog [block:code] { "codes": [ { "code": "UserKitWidget.open(dialog);", "language": "javascript", "name": "UserKitWidget.open(dialog)" } ] } [/block] If the dialog you are attempting to open requires a login, the user will be prompted to login first. [block:parameters] { "data": { "h-0": "Page ID", "h-1": "Description", "h-2": "Login Required?", "0-0": "change_password", "1-0": "forgot_password", "2-0": "login", "3-0": "register", "4-0": "settings", "5-0": "request_phone_verification_code", "6-0": "", "0-1": "Provides a form allowing users to change their current password", "0-2": "Yes", "1-1": "Prompts the user to enter the identifier used to login. They will receive an email with instructions to reset their password.", "1-2": "No", "2-2": "No", "2-1": "Login form", "3-1": "User registration form", "3-2": "No", "4-1": "Displays a form with the options for the current user to manage their user information", "4-2": "Yes", "5-1": "Used to validate phone numbers and change how a user logs in", "5-2": "No" }, "cols": 3, "rows": 6 } [/block] Close all open dialogs [block:code] { "codes": [ { "code": "UserKitWidget.dismiss();", "language": "text", "name": "UserKitWidget.dismiss();" } ] } [/block] Logout current user [block:code] { "codes": [ { "code": "UserKit.logout();", "language": "javascript", "name": "UserKit.logout()" } ] } [/block] Get current user data [block:code] { "codes": [ { "code": "UserKit.getUser();", "language": "text", "name": "UserKit.getUser()" } ] } [/block] Check if user is currently logged in [block:code] { "codes": [ { "code": "UserKit.isLoggedIn();", "language": "text", "name": "UserKit.isLoggedIn()" } ] } [/block]
{"_id":"58480add9b31af2d00062475","excerpt":"","githubsync":"","user":"555297897e64980d008d3baf","__v":0,"category":"5846c4ee5d064323007b1774","slug":"events-simple","type":"basic","updates":[],"version":"5589ceae9883a40d00c433f6","body":"Performing an action when the UserKitWidget has finished initialization:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"UserKitWidget.onInit = function() {\\n\\tconsole.log(\\\"onInit\\\");\\n};\",\n      \"language\": \"javascript\",\n      \"name\": \"UserKitWidget.onInit()\"\n    }\n  ]\n}\n[/block]\nPerforming an action when a user has logged in\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"UserKitWidget.onLogin = function() {\\n  console.log('onLogin');\\n};\",\n      \"language\": \"javascript\",\n      \"name\": \"UserKitWidget.onLogin()\"\n    }\n  ]\n}\n[/block]\nPerforming an action when an invite is accepted\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"UserKitWidget.onInviteAccepted = function(token) {\\n  console.log('onInviteAccepted');\\n};\",\n      \"language\": \"javascript\",\n      \"name\": \"UserKitWidget.onInviteAccepted()\"\n    }\n  ]\n}\n[/block]","isReference":false,"next":{"pages":[],"description":""},"order":3,"parentDoc":null,"createdAt":"2016-12-07T13:13:01.616Z","hidden":false,"link_external":false,"link_url":"","project":"5589ceae9883a40d00c433f3","sync_unique":"","title":"Events","api":{"results":{"codes":[{"code":"{}","name":"","status":200,"language":"json"},{"name":"","status":400,"language":"json","code":"{}"}]},"settings":"","auth":"required","params":[],"url":""},"childrenPages":[]}

Events


Performing an action when the UserKitWidget has finished initialization: [block:code] { "codes": [ { "code": "UserKitWidget.onInit = function() {\n\tconsole.log(\"onInit\");\n};", "language": "javascript", "name": "UserKitWidget.onInit()" } ] } [/block] Performing an action when a user has logged in [block:code] { "codes": [ { "code": "UserKitWidget.onLogin = function() {\n console.log('onLogin');\n};", "language": "javascript", "name": "UserKitWidget.onLogin()" } ] } [/block] Performing an action when an invite is accepted [block:code] { "codes": [ { "code": "UserKitWidget.onInviteAccepted = function(token) {\n console.log('onInviteAccepted');\n};", "language": "javascript", "name": "UserKitWidget.onInviteAccepted()" } ] } [/block]
Performing an action when the UserKitWidget has finished initialization: [block:code] { "codes": [ { "code": "UserKitWidget.onInit = function() {\n\tconsole.log(\"onInit\");\n};", "language": "javascript", "name": "UserKitWidget.onInit()" } ] } [/block] Performing an action when a user has logged in [block:code] { "codes": [ { "code": "UserKitWidget.onLogin = function() {\n console.log('onLogin');\n};", "language": "javascript", "name": "UserKitWidget.onLogin()" } ] } [/block] Performing an action when an invite is accepted [block:code] { "codes": [ { "code": "UserKitWidget.onInviteAccepted = function(token) {\n console.log('onInviteAccepted');\n};", "language": "javascript", "name": "UserKitWidget.onInviteAccepted()" } ] } [/block]
{"_id":"57d9f30c2bb38f0e00ef413b","project":"5589ceae9883a40d00c433f3","type":"post","hidden":false,"isReference":true,"order":0,"createdAt":"2016-09-15T01:02:04.532Z","link_url":"","next":{"pages":[],"description":""},"title":"Create a user","user":"5542d87d795b590d001dc7ff","__v":1,"api":{"settings":"","url":"/v1/users","auth":"required","examples":{"codes":[{"language":"curl","code":"curl https://api.userkit.io/v1/users \\\n -u api:{YOUR_APP_SECRET_KEY} \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"jane.smith@example.com\", \"password\": \"secretpass\"}'"},{"language":"python","code":"uk = userkit.UserKit(\"{YOUR_APP_SECRET_KEY}\")\n\nuser = uk.users.create_user(\n\temail=\"jane.smith@example.com\",\n\tpassword=\"secretpass\"\n)"},{"language":"ruby","code":"def create_user(data)\n    resource = RestClient::Resource.new(\n      \t'https://api.userkit.io/v1/users',\n      'api', \"{YOUR_APP_SECRET_KEY}\")\n    response = resource.post(data.to_json,\n        :content_type => 'application/json')\n    return JSON.parse(response.body)\nend\n\nuser = create_user({\n\t\"email\"=>\"jane.smith@example.com\",\n\t\"password\"=>\"secretpass\"\n})"},{"code":"package main\n\nimport (\n\t\"fmt\"\n\tuserkit \"github.com/workpail/userkit-go\"\n)\n\nfunc main() {\n  uk := userkit.NewUserKit(\n    \"{YOUR_APP_SECRET_KEY}\")\n  \n\tdata := map[string]string{\n    \"email\": \"jane.smith@example.com\",\n\t\t\"password\": \"secretpass\"}\n  \n\tuser, err := uk.Users.Create(data)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tfmt.Printf(\"%+v\", user)\n}","language":"go"},{"name":"PHP","language":"php","code":"<?php\n\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\n$user = $uk->users->createUser(['email' => 'jane.smith@example.com',\n\t'password' => 'secretpass']);\n"}]},"method":"post","params":[{"type":"string","name":"name","_id":"57d4aca7642d570e00ebd5b8","ref":"","in":"body","required":false,"desc":"The user's full name, e.g. \"Jane Smith\"","default":""},{"required":false,"desc":"A username","default":"","type":"string","name":"username","_id":"57d4aca7642d570e00ebd5b7","ref":"","in":"body"},{"ref":"","in":"body","required":false,"desc":"An email address","default":"","type":"string","name":"email","_id":"57d4aca7642d570e00ebd5b6"},{"default":"","type":"string","name":"password","_id":"57d4aca7642d570e00ebd5b5","ref":"","in":"body","required":false,"desc":"The user's password"},{"default":"","type":"string","name":"auth_type","_id":"57d4aca7642d570e00ebd5b4","ref":"","in":"body","required":false,"desc":"Can be one of \"password\", \"two_factor\", or \"one_time_password\""},{"default":"","type":"string","name":"phone","_id":"57d4aca7642d570e00ebd5b3","ref":"","in":"body","required":false,"desc":"A phone number"},{"default":"","type":"string","name":"verified_phone_token","_id":"57d4aca7642d570e00ebd5b2","ref":"","in":"body","required":false,"desc":"A token proving that the user owns the phone number"}],"results":{"codes":[{"language":"json","status":200,"name":"","code":"{\n  \"id\": \"usr_TgTbetyiSvuiIw\",\n  \"name\": \"Jane Smith\",\n  \"username\": \"janes5\",\n  \"email\": \"jane.smith@example.com\",\n  \"verified_email\": null,\n  \"verified_phone\": \"+15552323353\",\n  \"auth_type\": \"two_factor\",\n  \"disabled\": false,\n  \"created\": 1473544359.3973701,\n  \"last_failed_login\": null,\n  \"last_login\": null\n}"},{"status":400,"name":"","code":"{\n\t// Every error response contains an error property\n\t\"error\": {\n    \"type\": \"invalid_request_error\",\n    \"code\": \"invalid_username\",\n    \"param\": \"username\",\n    \"message\": \"Invalid username\"\n  },\n  \n  // But some error responses can contain multiple errors.\n  // In this case the \"errors\" property contains all of the errors.\n  \"errors\": [\n    {\n      \"type\": \"invalid_request_error\",\n      \"code\": \"invalid_username\",\n      \"param\": \"username\",\n      \"message\": \"Invalid username\"\n    },\n    {\n      \"type\": \"invalid_request_error\",\n      \"code\": \"invalid_email\",\n      \"param\": \"email\",\n      \"message\": \"Invalid email\"\n    }\n  ]\n}","language":"json"}]}},"category":"57d4a754899ab90e00105e5d","link_external":false,"parentDoc":null,"sync_unique":"","updates":[],"body":"[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"For the API explorer authentication: *username* should be \\\"api\\\", *password* should be the secret API key for a test UserKit app.\"\n}\n[/block]","excerpt":"Most of the time your users will signup using the widget, but you can also create users directly with the API","githubsync":"","slug":"create-a-user","version":"5589ceae9883a40d00c433f6","childrenPages":[]}

postCreate a user

Most of the time your users will signup using the widget, but you can also create users directly with the API

Body Params

name:
string
The user's full name, e.g. "Jane Smith"
username:
string
A username
email:
string
An email address
password:
string
The user's password
auth_type:
string
Can be one of "password", "two_factor", or "one_time_password"
phone:
string
A phone number
verified_phone_token:
string
A token proving that the user owns the phone number
[block:callout] { "type": "info", "body": "For the API explorer authentication: *username* should be \"api\", *password* should be the secret API key for a test UserKit app." } [/block]

User Information

Try It Out

post
{{ tryResults.results }}
Method{{ tryResults.method }}
Request Headers
{{ tryResults.requestHeaders }}
URL{{ tryResults.url }}
Request Data
{{ tryResults.data }}
Status
Response Headers
{{ tryResults.responseHeaders }}

Definition

{{ api_url }}{{ page_api_url }}

Examples


Result Format



[block:callout] { "type": "info", "body": "For the API explorer authentication: *username* should be \"api\", *password* should be the secret API key for a test UserKit app." } [/block]
{"_id":"57d9edd75740030e00f21263","title":"Fetch a user","user":"5542d87d795b590d001dc7ff","excerpt":"Get a user by id","hidden":false,"parentDoc":null,"slug":"fetch-a-user","sync_unique":"","api":{"examples":{"codes":[{"code":"curl https://api.userkit.io/v1/users/{USER_ID} \\\n -u api:{YOUR_APP_SECRET_KEY}","language":"curl"},{"code":"uk = userkit.UserKit(\"{YOUR_APP_SECRET_KEY}\")\n\nuser = uk.users.get_user(\"{USER_ID}\")","language":"python"},{"code":"def get_user(user_id)\n    url = 'https://api.userkit.io/v1/users/' +\n          user_id\n    resource = RestClient::Resource.new(url,\n      'api', '{YOUR_APP_SECRET_KEY}')\n    begin\n        response = resource.get()\n        return JSON.parse(response.body)\n    rescue RestClient::Exception\n        return nil\n    end\nend\n\n\nuser = get_user({USER_ID})","language":"ruby"},{"language":"go","code":"package main\n\nimport (\n\t\"fmt\"\n\tuserkit \"github.com/workpail/userkit-go\"\n)\n\nfunc main() {\n  uk := userkit.NewUserKit(\n    \"{YOUR_APP_SECRET_KEY}\")\n  \n  user, _ := uk.Users.Get(\"{USER_ID}\")\n\tfmt.Printf(\"%+v\", user)\n}"},{"language":"php","code":"<?php\n\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\n$user = $uk->users->getUser('<USER_ID>');\n"}]},"method":"get","params":[{"desc":"The ID of the user to fetch","default":"","type":"string","name":"user_id","_id":"57d9da2d5a2c4e0e00c306ee","ref":"","in":"path","required":false}],"results":{"codes":[{"language":"json","code":"{\n  \"id\": \"usr_TgTbetyiSvuiIw\",\n  \"name\": \"Jane Smith\",\n  \"username\": \"janes5\",\n  \"email\": \"jane.smith@example.com\",\n  \"verified_email\": null,\n  \"verified_phone\": \"+15552323353\",\n  \"auth_type\": \"two_factor\",\n  \"disabled\": false,\n  \"created\": 1473544359.3973701,\n  \"last_failed_login\": null,\n  \"last_login\": null\n}","name":"","status":200},{"code":"{\n  \"error\": {\n    \"type\": \"resource_not_found_error\",\n    \"code\": \"not_found\",\n    \"message\": \"Not found\"\n  }\n}","name":"","status":400,"language":"json"}]},"settings":"","url":"/v1/users/:user_id","auth":"required"},"body":"","createdAt":"2016-09-15T00:39:51.907Z","version":"5589ceae9883a40d00c433f6","isReference":true,"link_external":false,"link_url":"","project":"5589ceae9883a40d00c433f3","type":"get","__v":1,"category":"57d4a754899ab90e00105e5d","githubsync":"","next":{"description":"","pages":[]},"order":1,"updates":[],"childrenPages":[]}

getFetch a user

Get a user by id

Path Params

user_id:
string
The ID of the user to fetch

User Information

Try It Out

get
{{ tryResults.results }}
Method{{ tryResults.method }}
Request Headers
{{ tryResults.requestHeaders }}
URL{{ tryResults.url }}
Request Data
{{ tryResults.data }}
Status
Response Headers
{{ tryResults.responseHeaders }}

Definition

{{ api_url }}{{ page_api_url }}

Examples


Result Format



{"_id":"57d9d6f03916800e003ddf61","api":{"results":{"codes":[{"status":200,"language":"json","code":"{\n  \"id\": \"usr_TgTbetyiSvuiIw\",\n  \"name\": \"Jane Smith\",\n  \"username\": \"janes5\",\n  \"email\": \"jane.smith@example.com\",\n  \"verified_email\": null,\n  \"verified_phone\": \"+15552323353\",\n  \"auth_type\": \"two_factor\",\n  \"disabled\": false,\n  \"created\": 1473544359.3973701,\n  \"last_failed_login\": null,\n  \"last_login\": null\n}","name":""},{"status":400,"language":"json","code":"{\n\t// Every error response contains an error property\n\t\"error\": {\n    \"type\": \"invalid_request_error\",\n    \"code\": \"invalid_username\",\n    \"param\": \"username\",\n    \"message\": \"Invalid username\"\n  },\n  \n  // But some error responses can contain multiple errors.\n  // In this case the \"errors\" property contains all of the errors.\n  \"errors\": [\n    {\n      \"type\": \"invalid_request_error\",\n      \"code\": \"invalid_username\",\n      \"param\": \"username\",\n      \"message\": \"Invalid username\"\n    },\n    {\n      \"type\": \"invalid_request_error\",\n      \"code\": \"invalid_email\",\n      \"param\": \"email\",\n      \"message\": \"Invalid email\"\n    }\n  ]\n}","name":""}]},"settings":"","url":"/v1/users/:user_id","auth":"required","examples":{"codes":[{"code":"curl https://api.userkit.io/v1/users/{USER_ID} \\\n -u api:{YOUR_APP_SECRET_KEY} \\\n -H \"Content-Type: application/json\" \\\n -d '{\"name\": \"Jane Smith\", \"username\": \"jane5\"}'","language":"curl"},{"code":"uk = userkit.UserKit(\"{YOUR_APP_SECRET_KEY}\")\n\nuser = uk.users.update_user(\"{USER_ID}\",\n                            name=\"Jane Smith\")","language":"python"},{"code":"def update_user(user_id, data)\n  \turl = 'https://api.userkit.io/v1/users/' +\n    \t\t\tuser_id\n    resource = RestClient::Resource.new(url,\n      \t'api', '{YOUR_APP_SECRET_KEY}')\n    response = resource.post(\n        data.to_json,\n        :content_type => 'application/json')\n    return JSON.parse(response.body)\nend\n\n\nuser = update_user({USER_ID}, {\n  \"name\"=>\"Jane Smith\",\n  \"username\"=>\"janes5\"\n})","language":"ruby"},{"language":"go","code":"package main\n\nimport (\n\t\"fmt\"\n\tuserkit \"github.com/workpail/userkit-go\"\n)\n\nfunc main() {\n  uk := userkit.NewUserKit(\n    \"{YOUR_APP_SECRET_KEY}\")\n  \n\tdata := map[string]string{\n    \"name\": \"Jane Smith\"}\n  \n  user, _ := uk.Users.Update(\"{USER_ID}\",\n                             data)\n\tfmt.Printf(\"%+v\", user)\n}"},{"language":"php","code":"<?php\n\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\n$user = $uk->users->updateUser('<USER_ID>', ['name' => 'Jane Smith']);\n"}]},"method":"post","params":[{"_id":"57d4aca7642d570e00ebd5b8","ref":"","in":"body","required":false,"desc":"The user's full name, e.g. \"Jane Smith\"","default":"","type":"string","name":"name"},{"name":"username","_id":"57d4aca7642d570e00ebd5b7","ref":"","in":"body","required":false,"desc":"A username","default":"","type":"string"},{"ref":"","in":"body","required":false,"desc":"An email address","default":"","type":"string","name":"email","_id":"57d4aca7642d570e00ebd5b6"},{"in":"body","required":false,"desc":"The user's password","default":"","type":"string","name":"password","_id":"57d4aca7642d570e00ebd5b5","ref":""},{"desc":"Can be one of \"password\", \"two_factor\", or \"one_time_password\"","default":"","type":"string","name":"auth_type","_id":"57d4aca7642d570e00ebd5b4","ref":"","in":"body","required":false},{"name":"phone","_id":"57d4aca7642d570e00ebd5b3","ref":"","in":"body","required":false,"desc":"A phone number","default":"","type":"string"},{"type":"string","name":"verified_phone_token","_id":"57d4aca7642d570e00ebd5b2","ref":"","in":"body","required":false,"desc":"A token proving that the user owns the phone number","default":""},{"desc":"The ID of the user to update","default":"","type":"string","name":"user_id","_id":"57d9da2d5a2c4e0e00c306ee","ref":"","in":"path","required":false}]},"parentDoc":null,"sync_unique":"","updates":[],"body":"","category":"57d4a754899ab90e00105e5d","isReference":true,"link_url":"","next":{"description":"","pages":[]},"project":"5589ceae9883a40d00c433f3","__v":2,"createdAt":"2016-09-14T23:02:08.600Z","githubsync":"","hidden":false,"link_external":false,"slug":"update-a-user","title":"Update a user","version":"5589ceae9883a40d00c433f6","excerpt":"Your users can manage their own settings in the widget, but you can also update users with the API","order":2,"type":"post","user":"5542d87d795b590d001dc7ff","childrenPages":[]}

postUpdate a user

Your users can manage their own settings in the widget, but you can also update users with the API

Path Params

user_id:
string
The ID of the user to update

Body Params

name:
string
The user's full name, e.g. "Jane Smith"
username:
string
A username
email:
string
An email address
password:
string
The user's password
auth_type:
string
Can be one of "password", "two_factor", or "one_time_password"
phone:
string
A phone number
verified_phone_token:
string
A token proving that the user owns the phone number

User Information

Try It Out

post
{{ tryResults.results }}
Method{{ tryResults.method }}
Request Headers
{{ tryResults.requestHeaders }}
URL{{ tryResults.url }}
Request Data
{{ tryResults.data }}
Status
Response Headers
{{ tryResults.responseHeaders }}

Definition

{{ api_url }}{{ page_api_url }}

Examples


Result Format



{"_id":"57efe21845f5d92200b8e2db","link_external":false,"next":{"description":"","pages":[]},"slug":"login-a-user","category":"57d4a754899ab90e00105e5d","createdAt":"2016-10-01T16:19:36.357Z","excerpt":"Your users can login with the widget, but you can also login a user directly via the API","hidden":false,"version":"5589ceae9883a40d00c433f6","type":"post","updates":[],"user":"5542d87d795b590d001dc7ff","__v":1,"body":"","link_url":"","order":3,"parentDoc":null,"githubsync":"","sync_unique":"","title":"Login a user","api":{"results":{"codes":[{"name":"","code":"{\n  \"token\": \"usr_j3LB5QPAH8B9UD:KJmrd2N4O4tgE1AkZMoX0tPhlTT1NDQfVblRJ96ln2G|sha256\", \n  \"expires_in_secs\": 86399.832370000004, \n  \"refresh_after_secs\": 77759.832439999998\n}","language":"json","status":200},{"code":"{\n  \"error\": {\n    \"type\": \"user_authentication_error\",\n    \"code\": \"unauthorized\",\n    \"message\": \"Wrong login or password.\",\n    \"retry_wait\": 30.0  // Or null\n  }\n}","language":"json","status":400,"name":""}]},"settings":"","url":"/v1/users/login","auth":"required","examples":{"codes":[{"code":"curl https://api.userkit.io/v1/users/login \\\n -u api:{YOUR_APP_SECRET_KEY} \\\n -H \"Content-Type: application/json\" \\\n -d '{\"username\": \"jane.smith@example.com\", \"password\": \"secretpass\"}'","language":"curl"},{"code":"uk = userkit.UserKit(\"{YOUR_APP_SECRET_KEY}\")\n\n# param 1: email, username or phone.\n# param 2: password.\n# param 3 (OPTIONAL): 2-factor or on-demand\n# \t\t\t\tlogin code.\nsession = uk.users.login_user(\n  \"jane.smith@example.com\", \"secretpass\")","language":"python"},{"language":"ruby","code":"def login_user(username, password=nil,\n  \t\t\t\t\t\tlogin_code=nil)\n    url = 'https://api.userkit.io/v1/users/login'\n    resource = RestClient::Resource.new(url,\n      'api', '{YOUR_APP_SECRET_KEY}')\n    data = {:username => username}\n    if password\n        data['password'] = password\n    end\n    if login_code\n        data['login_code'] = login_code\n    end\n    response = resource.post(\n        data.to_json,\n        :content_type => 'application/json')\n    return JSON.parse(response.body)\nend\n\n# Param 1: email, username or phone.\n# Param 2: password.\n# Param 3 (optional): 2-factor or on-demand\n#\t\t\t\t\tlogin code.\nsession = login_user(\"jane.smith@example.com\",\n  \"secretpass\")"},{"code":"package main\n\nimport (\n\t\"fmt\"\n\tuserkit \"github.com/workpail/userkit-go\"\n)\n\nfunc main() {\n  uk := userkit.NewUserKit(\n    \"{YOUR_APP_SECRET_KEY}\")\n  \n  // param 1: username, email or phone\n  // param 2: password\n  // param 3: OPTIONAL 2-factor or on-demand\n  //          login code\n  session, _ := uk.Users.Login(\n    \"js@example.com\", \"secretpass\", \"\")\n\tfmt.Printf(\"%+v\", user)\n}","language":"go"},{"language":"php","code":"<?php\n\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\n// param 1: email, username or phone.\n// param 2: password.\n// param 3 (OPTIONAL): 2-factor or on-demand\n// \t\t\t\tlogin code.\n$session = $uk->users->loginUser('jane.smith@example.com', 'secretpass');"}]},"method":"post","params":[{"required":false,"desc":"A user identifier, this can be a username, email or phone number","default":"","type":"string","name":"username","_id":"57efddcc8daa662b00d94fdc","ref":"","in":"body"},{"type":"string","name":"password","_id":"57efddcc8daa662b00d94fdb","ref":"","in":"body","required":false,"desc":"The user's password","default":""},{"required":false,"desc":"OPTIONAL, a two-factor or on-demand login code if user's account has this turned on","default":"","type":"string","name":"login_code","_id":"57efddcc8daa662b00d94fda","ref":"","in":"body"}]},"isReference":true,"project":"5589ceae9883a40d00c433f3","childrenPages":[]}

postLogin a user

Your users can login with the widget, but you can also login a user directly via the API

Body Params

username:
string
A user identifier, this can be a username, email or phone number
password:
string
The user's password
login_code:
string
OPTIONAL, a two-factor or on-demand login code if user's account has this turned on

User Information

Try It Out

post
{{ tryResults.results }}
Method{{ tryResults.method }}
Request Headers
{{ tryResults.requestHeaders }}
URL{{ tryResults.url }}
Request Data
{{ tryResults.data }}
Status
Response Headers
{{ tryResults.responseHeaders }}

Definition

{{ api_url }}{{ page_api_url }}

Examples


Result Format



{"_id":"57efe333dbc6523200f268fc","isReference":true,"order":4,"slug":"fetch-a-logged-in-user-by-session","category":"57d4a754899ab90e00105e5d","body":"","link_external":false,"sync_unique":"","type":"get","updates":[],"api":{"results":{"codes":[{"language":"json","code":"{\n  \"id\": \"usr_TgTbetyiSvuiIw\",\n  \"name\": \"Jane Smith\",\n  \"username\": \"janes5\",\n  \"email\": \"jane.smith@example.com\",\n  \"verified_email\": null,\n  \"verified_phone\": \"+15552323353\",\n  \"auth_type\": \"two_factor\",\n  \"disabled\": false,\n  \"created\": 1473544359.3973701,\n  \"last_failed_login\": null,\n  \"last_login\": null\n}","name":"","status":200},{"status":400,"language":"json","code":"{\n  \"error\": {\n    \"type\": \"user_authentication_error\",\n    \"code\": \"unauthorized\",\n    \"message\": \"User unauthorized\",\n    \"retry_wait\": null\n  }\n}","name":""}]},"settings":"","url":"/v1/users/by_token","auth":"required","examples":{"codes":[{"code":"curl https://api.userkit.io/v1/users/by_token \\\n -u api:sk_atKYtmX64nGRWbvuv6FXq2CG.app_6fa64vtE \\\n -H \"X-User-Token: {SESSION_TOKEN}\"","language":"curl"},{"code":"uk = userkit.UserKit(\"{YOUR_APP_SECRET_KEY}\")\n\nuser = uk.users.get_current_user(\n  \"{SESSION_TOKEN}\")","language":"python"},{"code":"require 'json'\nrequire 'rest-client'\n\ndef get_current_user(session_token)\n  resource = RestClient::Resource.new(\n    'https://api.userkit.io/v1/users/by_token',\n    'api', '{YOUR_APP_SECRET_KEY}')\n  begin\n \t\tresponse = resource.get(:'X-User-TOken' => session_token)\n    return JSON.parse(response.body)\n \trescue RestClient::Exception\n  \treturn nil\n  end\nend\n\n\nuser = get_current_user(\"{SESSION_TOKEN}\")","language":"ruby"},{"language":"go","code":"package main\n\nimport (\n\t\"fmt\"\n\tuserkit \"github.com/workpail/userkit-go\"\n)\n\nfunc main() {\n  uk := userkit.NewUserKit(\n    \"{YOUR_APP_SECRET_KEY}\")\n    \n  user, _ := uk.Users.GetUserBySession(\n    \"{SESSION_TOKEN}\")\n\tfmt.Printf(\"%+v\", user)\n}"},{"language":"php","code":"<?php\n\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\n$user = $uk->users->getCurrentUser('<SESSION_TOKEN>');"}]},"method":"get","params":[{"desc":"The session token for a logged in user","default":"","type":"string","name":"X-User-Token","_id":"57efe3d62b028c3400e6bed6","ref":"","in":"header","required":false}]},"githubsync":"","link_url":"","title":"Fetch a logged in user by session","user":"5542d87d795b590d001dc7ff","createdAt":"2016-10-01T16:24:19.352Z","excerpt":"Use a session token to get the logged in user","hidden":false,"next":{"description":"","pages":[]},"parentDoc":null,"project":"5589ceae9883a40d00c433f3","version":"5589ceae9883a40d00c433f6","__v":2,"childrenPages":[]}

getFetch a logged in user by session

Use a session token to get the logged in user

Headers

X-User-Token:
string
The session token for a logged in user

User Information

Try It Out

get
{{ tryResults.results }}
Method{{ tryResults.method }}
Request Headers
{{ tryResults.requestHeaders }}
URL{{ tryResults.url }}
Request Data
{{ tryResults.data }}
Status
Response Headers
{{ tryResults.responseHeaders }}

Definition

{{ api_url }}{{ page_api_url }}

Examples


Result Format



{"_id":"5807cb096d47320f007a301b","category":"5807813b6d24211900953b99","createdAt":"2016-10-19T19:35:37.844Z","isReference":false,"link_external":false,"user":"5542d87d795b590d001dc7ff","api":{"results":{"codes":[{"status":200,"language":"json","code":"{}","name":""},{"status":400,"language":"json","code":"{}","name":""}]},"auth":"required","params":[],"url":"","settings":""},"body":"Invites are useful for the following scenarios:\n\n* Invite someone to signup to your app or website.\n* Invite someone on behalf of one of your user's, e.g. to track and reward when one of your users successfully invites their friends to join your app.\n* Custom scenarios, such as securely inviting a user to access a shared document or join a team, are supported using the `invite.extras` property, for example by storing a document or team ID.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n  \\\"id\\\": \\\"invt_LfbrvhnlUAyM1N\\\",\\n  \\\"token_raw\\\": \\\"invt_LfbrvhnlUAyM1N-ReHwpMKWj5NIY0pv3x0NcurW\\\",\\n  \\\"invite_url\\\": \\\"https://api.userkit.io/hosted_widget?app=app_6fa64vtE&amp;invt=invt_LfbrvhnlUAyM1N-ReHwpMKWj5NIY0pv3x0NcurW\\\", \\n  \\\"app_id\\\": \\\"app_6fa64vtE\\\", \\n  \\\"from_user\\\": null, \\n  \\\"accepted\\\": false, \\n  \\\"expires_secs\\\": 604800, \\n  \\\"to_email\\\": \\\"jane.smith@example.com\\\", \\n  \\\"created\\\": 1476888188.08038, \\n  \\\"extras\\\": null, \\n  \\\"accepted_user\\\": null, \\n  \\\"accepted_date\\\": null\\n}\",\n      \"language\": \"json\",\n      \"name\": \"Newly created Invite\"\n    }\n  ],\n  \"sidebar\": true\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"`token_raw` and `invite_url` should be handled carefully. Remember, anyone who has access to an invite-url or token can accept the invite.\\n\\nNote: These properties are only present at the time the invite is created. If you fetch an existing invite later on you won't have access to these properties.\"\n}\n[/block]","hidden":false,"link_url":"","parentDoc":null,"updates":[],"__v":0,"order":0,"project":"5589ceae9883a40d00c433f3","sync_unique":"","excerpt":"","githubsync":"","slug":"invites-overview","title":"Invites overview","type":"basic","version":"5589ceae9883a40d00c433f6","childrenPages":[]}

Invites overview


Invites are useful for the following scenarios: * Invite someone to signup to your app or website. * Invite someone on behalf of one of your user's, e.g. to track and reward when one of your users successfully invites their friends to join your app. * Custom scenarios, such as securely inviting a user to access a shared document or join a team, are supported using the `invite.extras` property, for example by storing a document or team ID. [block:code] { "codes": [ { "code": "{\n \"id\": \"invt_LfbrvhnlUAyM1N\",\n \"token_raw\": \"invt_LfbrvhnlUAyM1N-ReHwpMKWj5NIY0pv3x0NcurW\",\n \"invite_url\": \"https://api.userkit.io/hosted_widget?app=app_6fa64vtE&amp;invt=invt_LfbrvhnlUAyM1N-ReHwpMKWj5NIY0pv3x0NcurW\", \n \"app_id\": \"app_6fa64vtE\", \n \"from_user\": null, \n \"accepted\": false, \n \"expires_secs\": 604800, \n \"to_email\": \"jane.smith@example.com\", \n \"created\": 1476888188.08038, \n \"extras\": null, \n \"accepted_user\": null, \n \"accepted_date\": null\n}", "language": "json", "name": "Newly created Invite" } ], "sidebar": true } [/block] [block:callout] { "type": "warning", "body": "`token_raw` and `invite_url` should be handled carefully. Remember, anyone who has access to an invite-url or token can accept the invite.\n\nNote: These properties are only present at the time the invite is created. If you fetch an existing invite later on you won't have access to these properties." } [/block]
Invites are useful for the following scenarios: * Invite someone to signup to your app or website. * Invite someone on behalf of one of your user's, e.g. to track and reward when one of your users successfully invites their friends to join your app. * Custom scenarios, such as securely inviting a user to access a shared document or join a team, are supported using the `invite.extras` property, for example by storing a document or team ID. [block:code] { "codes": [ { "code": "{\n \"id\": \"invt_LfbrvhnlUAyM1N\",\n \"token_raw\": \"invt_LfbrvhnlUAyM1N-ReHwpMKWj5NIY0pv3x0NcurW\",\n \"invite_url\": \"https://api.userkit.io/hosted_widget?app=app_6fa64vtE&amp;invt=invt_LfbrvhnlUAyM1N-ReHwpMKWj5NIY0pv3x0NcurW\", \n \"app_id\": \"app_6fa64vtE\", \n \"from_user\": null, \n \"accepted\": false, \n \"expires_secs\": 604800, \n \"to_email\": \"jane.smith@example.com\", \n \"created\": 1476888188.08038, \n \"extras\": null, \n \"accepted_user\": null, \n \"accepted_date\": null\n}", "language": "json", "name": "Newly created Invite" } ], "sidebar": true } [/block] [block:callout] { "type": "warning", "body": "`token_raw` and `invite_url` should be handled carefully. Remember, anyone who has access to an invite-url or token can accept the invite.\n\nNote: These properties are only present at the time the invite is created. If you fetch an existing invite later on you won't have access to these properties." } [/block]
{"_id":"580fd36a02070b3b008c1495","__v":1,"createdAt":"2016-10-25T21:49:30.247Z","isReference":true,"link_external":false,"link_url":"","next":{"description":"","pages":[]},"order":2,"type":"basic","user":"5542d87d795b590d001dc7ff","api":{"results":{"codes":[{"status":200,"language":"json","code":"{}","name":""},{"code":"{}","name":"","status":400,"language":"json"}]},"auth":"required","params":[],"url":"","settings":""},"category":"5807813b6d24211900953b99","githubsync":"","hidden":false,"parentDoc":null,"body":"How to create, send, and (optionally) process an invite-accepted event.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"1. Create an Invite\"\n}\n[/block]\nYou can create a secure invite with UserKit's Invite API. This creates an invite object with a secret URL which you can send out in an email.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"curl https://api.userkit.io/v1/invites \\\\\\n -u api:<YOUR_APP_SECRET_KEY> \\\\\\n -H \\\"Content-Type: application/json\\\" \\\\\\n -d '{\\\"to_email\\\": \\\"jane.smith@example.com\\\", \\\"extras\\\": {\\\"doc_id\\\": \\\"ab123\\\"}}'\",\n      \"language\": \"curl\"\n    },\n    {\n      \"code\": \"uk = userkit.UserKit(\\\"<YOUR_APP_SECRET_KEY>\\\")\\n\\ninvite = uk.invites.create_invite(to_email=\\\"jane.smith@example.com\\\")\",\n      \"language\": \"python\"\n    },\n    {\n      \"code\": \"<?php\\n\\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\\n\\n$invite = $uk->invites->createInvite(['to_email' => 'jane.smith@example.com');\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"2. Send the invite URL\"\n}\n[/block]\nNow that you've created an invite, you can send the URL stored in `invite.invite_url` by email, SMS, or however you like.\n\nHow you do this is up to you, but you might consider a third-party email service like Mailgun (https://mailgun.com), SendGrid (https://sendgrid.com) or MailJet (https://mjml.io).\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"# Send an email containing the invite url\\nemail_body = \\\"To join our app click here: {}\\\".format(invite.invite_url)\\nsend_email(to='jane.smith@example.com', body=email_body)\",\n      \"language\": \"python\"\n    },\n    {\n      \"code\": \"<?php\\n\\n// Send an email containing the invite url\\n$email_body = \\\"To join our app click here: $invite->invite_url\\\";\\nsend_email(['to' => 'jane.smith@example.com', 'body' => $email_body);\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nWhen the recipient clicks on the invite link, the invite object will be updated (`accepted` will be set to true,  and `accepted_user` will be set to this user's id).\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"By default, invite URLs point to a page hosted by UserKit. You can change this to a page on your own domain where you host the UserKit [widget](/docs/quickstart), such as your account page. See the \\\"Widget URL\\\" section in the [dashboard](https://dashboard.userkit.io) under Settings.\"\n}\n[/block]\nIf you want to do something special (like add the invited user to a team, or grant them access to a shared document) see step 3, otherwise you're finished!\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"3. Handle invite-accepted callback (optional)\"\n}\n[/block]\nIf you want to do something special when an invite is accepted, such as add the invited user to a team or give them access to a shared document, you can override the `UserKit.onInviteAccepted()` method on the page where you are hosting the widget.\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"When you create an invite you can add some custom data to it by passing in the `extras` parameter. When you get the invite later on you can access that custom data in the `invite.extras` property. In this example we assume the invite was created with an extras parameter containing `{\\\"doc_id\\\": \\\"ab123\\\"}`.\"\n}\n[/block]\nIn this example the invited user will be added to the list of editors for the document, and then redirected to view that document:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<script type=\\\"application/javascript\\\">\\n  UserKitWidget.onInviteAccepted = function(token) {\\n    // POST the invite token to your server (we're using JQuery)\\n    $.post('/accept_invite', {'token': token}, function (response) {\\n     \\t// Now that your server has processed the invite, giving the\\n      // invited user access to the document, redirect them to that\\n      // document.\\n      window.location.href = '/doc/' + response['doc_id'];\\n    }, 'json');\\n  };\\n</script>\",\n      \"language\": \"html\"\n    }\n  ]\n}\n[/block]\nOn your server, setup a request handler for the `/accept_invite` endpoint. Here you can add the invited user to the list of users who are allowed to edit the document:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"import json\\nimport userkit\\n\\nuk = userkit.UserKit(\\\"<YOUR_APP_SECRET_KEY>\\\")\\n\\n# Portions of following snippet is pseudo code\\ndef accept_invite_handler(request, response):\\n\\tjson_body = json.loads(request.body)\\n  \\n  invite = uk.invites.get_once(json_body['token'])\\n  if not invite or not invite.accepted:\\n    # Invite token may be invalid or expired. Abort.\\n    response.set_status(400)\\n    return\\n\\n  # Add the invited user's ID to the list of editors for this\\n  # document\\n  doc = get_doc_from_db(invite.extras['doc_id'])\\n  doc.editors.append(invite.accepted_user)\\n  doc.save()\\n\\n  # Return the ID of the document, so your frontend JavaScript\\n  # code can redirect the user to that document\\n  json_resp = json.dumps({'doc_id': doc.id})\\n  response.write(json_resp) \",\n      \"language\": \"python\",\n      \"name\": null\n    },\n    {\n      \"code\": \"<?php\\n\\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\\n\\n// Portions of following snippet is pseudo code\\nfunction accept_invite_handler($request, $response)\\n{\\n  global $uk;\\n  \\n  // convert the body response to a json array type \\n  $json_body = json_decode($response->body, true);\\n  \\n  $invite = $uk->invites->getOnce($json_body['token']);\\n  if (!$invite || !$invite->accepted)\\n  {\\n    // Invite token may be invalid or expired. Abort.\\n    $response->set_status(400);\\n    return;\\n  }\\n\\n  // Add the invited user's ID to the list of editors for this\\n  // document\\n  $doc = get_doc_from_db($invite->extras['doc_id']);\\n  $doc->editors->append($invite->accepted_user);\\n  $doc->save();\\n\\n  // Return the ID of the document, so your frontend JavaScript\\n  // code can redirect the user to that document\\n  $json_resp = ['doc_id' => $doc->id];\\n  $response->write($json_resp);\\n}\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]","excerpt":"","project":"5589ceae9883a40d00c433f3","slug":"invites-quickstart","sync_unique":"","title":"Invites quickstart","updates":[],"version":"5589ceae9883a40d00c433f6","childrenPages":[]}

Invites quickstart


How to create, send, and (optionally) process an invite-accepted event. [block:api-header] { "type": "basic", "title": "1. Create an Invite" } [/block] You can create a secure invite with UserKit's Invite API. This creates an invite object with a secret URL which you can send out in an email. [block:code] { "codes": [ { "code": "curl https://api.userkit.io/v1/invites \\\n -u api:<YOUR_APP_SECRET_KEY> \\\n -H \"Content-Type: application/json\" \\\n -d '{\"to_email\": \"jane.smith@example.com\", \"extras\": {\"doc_id\": \"ab123\"}}'", "language": "curl" }, { "code": "uk = userkit.UserKit(\"<YOUR_APP_SECRET_KEY>\")\n\ninvite = uk.invites.create_invite(to_email=\"jane.smith@example.com\")", "language": "python" }, { "code": "<?php\n\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\n$invite = $uk->invites->createInvite(['to_email' => 'jane.smith@example.com');", "language": "php" } ] } [/block] [block:api-header] { "type": "basic", "title": "2. Send the invite URL" } [/block] Now that you've created an invite, you can send the URL stored in `invite.invite_url` by email, SMS, or however you like. How you do this is up to you, but you might consider a third-party email service like Mailgun (https://mailgun.com), SendGrid (https://sendgrid.com) or MailJet (https://mjml.io). [block:code] { "codes": [ { "code": "# Send an email containing the invite url\nemail_body = \"To join our app click here: {}\".format(invite.invite_url)\nsend_email(to='jane.smith@example.com', body=email_body)", "language": "python" }, { "code": "<?php\n\n// Send an email containing the invite url\n$email_body = \"To join our app click here: $invite->invite_url\";\nsend_email(['to' => 'jane.smith@example.com', 'body' => $email_body);", "language": "php" } ] } [/block] When the recipient clicks on the invite link, the invite object will be updated (`accepted` will be set to true, and `accepted_user` will be set to this user's id). [block:callout] { "type": "info", "body": "By default, invite URLs point to a page hosted by UserKit. You can change this to a page on your own domain where you host the UserKit [widget](/docs/quickstart), such as your account page. See the \"Widget URL\" section in the [dashboard](https://dashboard.userkit.io) under Settings." } [/block] If you want to do something special (like add the invited user to a team, or grant them access to a shared document) see step 3, otherwise you're finished! [block:api-header] { "type": "basic", "title": "3. Handle invite-accepted callback (optional)" } [/block] If you want to do something special when an invite is accepted, such as add the invited user to a team or give them access to a shared document, you can override the `UserKit.onInviteAccepted()` method on the page where you are hosting the widget. [block:callout] { "type": "info", "body": "When you create an invite you can add some custom data to it by passing in the `extras` parameter. When you get the invite later on you can access that custom data in the `invite.extras` property. In this example we assume the invite was created with an extras parameter containing `{\"doc_id\": \"ab123\"}`." } [/block] In this example the invited user will be added to the list of editors for the document, and then redirected to view that document: [block:code] { "codes": [ { "code": "<script type=\"application/javascript\">\n UserKitWidget.onInviteAccepted = function(token) {\n // POST the invite token to your server (we're using JQuery)\n $.post('/accept_invite', {'token': token}, function (response) {\n \t// Now that your server has processed the invite, giving the\n // invited user access to the document, redirect them to that\n // document.\n window.location.href = '/doc/' + response['doc_id'];\n }, 'json');\n };\n</script>", "language": "html" } ] } [/block] On your server, setup a request handler for the `/accept_invite` endpoint. Here you can add the invited user to the list of users who are allowed to edit the document: [block:code] { "codes": [ { "code": "import json\nimport userkit\n\nuk = userkit.UserKit(\"<YOUR_APP_SECRET_KEY>\")\n\n# Portions of following snippet is pseudo code\ndef accept_invite_handler(request, response):\n\tjson_body = json.loads(request.body)\n \n invite = uk.invites.get_once(json_body['token'])\n if not invite or not invite.accepted:\n # Invite token may be invalid or expired. Abort.\n response.set_status(400)\n return\n\n # Add the invited user's ID to the list of editors for this\n # document\n doc = get_doc_from_db(invite.extras['doc_id'])\n doc.editors.append(invite.accepted_user)\n doc.save()\n\n # Return the ID of the document, so your frontend JavaScript\n # code can redirect the user to that document\n json_resp = json.dumps({'doc_id': doc.id})\n response.write(json_resp) ", "language": "python", "name": null }, { "code": "<?php\n\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\n// Portions of following snippet is pseudo code\nfunction accept_invite_handler($request, $response)\n{\n global $uk;\n \n // convert the body response to a json array type \n $json_body = json_decode($response->body, true);\n \n $invite = $uk->invites->getOnce($json_body['token']);\n if (!$invite || !$invite->accepted)\n {\n // Invite token may be invalid or expired. Abort.\n $response->set_status(400);\n return;\n }\n\n // Add the invited user's ID to the list of editors for this\n // document\n $doc = get_doc_from_db($invite->extras['doc_id']);\n $doc->editors->append($invite->accepted_user);\n $doc->save();\n\n // Return the ID of the document, so your frontend JavaScript\n // code can redirect the user to that document\n $json_resp = ['doc_id' => $doc->id];\n $response->write($json_resp);\n}", "language": "php" } ] } [/block]
How to create, send, and (optionally) process an invite-accepted event. [block:api-header] { "type": "basic", "title": "1. Create an Invite" } [/block] You can create a secure invite with UserKit's Invite API. This creates an invite object with a secret URL which you can send out in an email. [block:code] { "codes": [ { "code": "curl https://api.userkit.io/v1/invites \\\n -u api:<YOUR_APP_SECRET_KEY> \\\n -H \"Content-Type: application/json\" \\\n -d '{\"to_email\": \"jane.smith@example.com\", \"extras\": {\"doc_id\": \"ab123\"}}'", "language": "curl" }, { "code": "uk = userkit.UserKit(\"<YOUR_APP_SECRET_KEY>\")\n\ninvite = uk.invites.create_invite(to_email=\"jane.smith@example.com\")", "language": "python" }, { "code": "<?php\n\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\n$invite = $uk->invites->createInvite(['to_email' => 'jane.smith@example.com');", "language": "php" } ] } [/block] [block:api-header] { "type": "basic", "title": "2. Send the invite URL" } [/block] Now that you've created an invite, you can send the URL stored in `invite.invite_url` by email, SMS, or however you like. How you do this is up to you, but you might consider a third-party email service like Mailgun (https://mailgun.com), SendGrid (https://sendgrid.com) or MailJet (https://mjml.io). [block:code] { "codes": [ { "code": "# Send an email containing the invite url\nemail_body = \"To join our app click here: {}\".format(invite.invite_url)\nsend_email(to='jane.smith@example.com', body=email_body)", "language": "python" }, { "code": "<?php\n\n// Send an email containing the invite url\n$email_body = \"To join our app click here: $invite->invite_url\";\nsend_email(['to' => 'jane.smith@example.com', 'body' => $email_body);", "language": "php" } ] } [/block] When the recipient clicks on the invite link, the invite object will be updated (`accepted` will be set to true, and `accepted_user` will be set to this user's id). [block:callout] { "type": "info", "body": "By default, invite URLs point to a page hosted by UserKit. You can change this to a page on your own domain where you host the UserKit [widget](/docs/quickstart), such as your account page. See the \"Widget URL\" section in the [dashboard](https://dashboard.userkit.io) under Settings." } [/block] If you want to do something special (like add the invited user to a team, or grant them access to a shared document) see step 3, otherwise you're finished! [block:api-header] { "type": "basic", "title": "3. Handle invite-accepted callback (optional)" } [/block] If you want to do something special when an invite is accepted, such as add the invited user to a team or give them access to a shared document, you can override the `UserKit.onInviteAccepted()` method on the page where you are hosting the widget. [block:callout] { "type": "info", "body": "When you create an invite you can add some custom data to it by passing in the `extras` parameter. When you get the invite later on you can access that custom data in the `invite.extras` property. In this example we assume the invite was created with an extras parameter containing `{\"doc_id\": \"ab123\"}`." } [/block] In this example the invited user will be added to the list of editors for the document, and then redirected to view that document: [block:code] { "codes": [ { "code": "<script type=\"application/javascript\">\n UserKitWidget.onInviteAccepted = function(token) {\n // POST the invite token to your server (we're using JQuery)\n $.post('/accept_invite', {'token': token}, function (response) {\n \t// Now that your server has processed the invite, giving the\n // invited user access to the document, redirect them to that\n // document.\n window.location.href = '/doc/' + response['doc_id'];\n }, 'json');\n };\n</script>", "language": "html" } ] } [/block] On your server, setup a request handler for the `/accept_invite` endpoint. Here you can add the invited user to the list of users who are allowed to edit the document: [block:code] { "codes": [ { "code": "import json\nimport userkit\n\nuk = userkit.UserKit(\"<YOUR_APP_SECRET_KEY>\")\n\n# Portions of following snippet is pseudo code\ndef accept_invite_handler(request, response):\n\tjson_body = json.loads(request.body)\n \n invite = uk.invites.get_once(json_body['token'])\n if not invite or not invite.accepted:\n # Invite token may be invalid or expired. Abort.\n response.set_status(400)\n return\n\n # Add the invited user's ID to the list of editors for this\n # document\n doc = get_doc_from_db(invite.extras['doc_id'])\n doc.editors.append(invite.accepted_user)\n doc.save()\n\n # Return the ID of the document, so your frontend JavaScript\n # code can redirect the user to that document\n json_resp = json.dumps({'doc_id': doc.id})\n response.write(json_resp) ", "language": "python", "name": null }, { "code": "<?php\n\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\n// Portions of following snippet is pseudo code\nfunction accept_invite_handler($request, $response)\n{\n global $uk;\n \n // convert the body response to a json array type \n $json_body = json_decode($response->body, true);\n \n $invite = $uk->invites->getOnce($json_body['token']);\n if (!$invite || !$invite->accepted)\n {\n // Invite token may be invalid or expired. Abort.\n $response->set_status(400);\n return;\n }\n\n // Add the invited user's ID to the list of editors for this\n // document\n $doc = get_doc_from_db($invite->extras['doc_id']);\n $doc->editors->append($invite->accepted_user);\n $doc->save();\n\n // Return the ID of the document, so your frontend JavaScript\n // code can redirect the user to that document\n $json_resp = ['doc_id' => $doc->id];\n $response->write($json_resp);\n}", "language": "php" } ] } [/block]
{"_id":"581a19d9539e760f00254079","category":"5819154bf62fee0f00949855","slug":"overview-custom-domain-emails","updates":[],"title":"Overview - custom domain emails","user":"5542d87d795b590d001dc7ff","excerpt":"","isReference":false,"link_external":false,"order":0,"parentDoc":null,"version":"5589ceae9883a40d00c433f6","body":"We recommend having emails sent from your own domain (for example no-reply@yourdomain.com). \n\nOnce you have enabled custom-domain emails, UserKit will be able to make requests to an endpoint on your server to have an email sent from your domain whenever needed. Here are some reasons you should enable custom-domain emails:\n\n* UserKit emails such as password-reset, registration, invites, will be sent from your own no-reply@yourdomain.com email address. By default emails are sent from UserKit's own email address.\n* Email links such as for password-reset and invites can send users to your own domain using the `widget_url` on your UserKit settings page (for example https://<yourdomain>.com/account). Without custom-domain email, links will always send your users to UserKit's own hosted widget page instead.\n* The send-invite feature will be enabled allowing you to send an invite with a single line of code. This feature is only enabled for apps with custom-domain email setup.","link_url":"","next":{"pages":[],"description":""},"sync_unique":"","type":"basic","__v":0,"api":{"params":[],"url":"","results":{"codes":[{"name":"","status":200,"language":"json","code":"{}"},{"language":"json","code":"{}","name":"","status":400}]},"settings":"","auth":"required"},"createdAt":"2016-11-02T16:52:41.806Z","githubsync":"","hidden":false,"project":"5589ceae9883a40d00c433f3","childrenPages":[]}

Overview - custom domain emails


We recommend having emails sent from your own domain (for example no-reply@yourdomain.com). Once you have enabled custom-domain emails, UserKit will be able to make requests to an endpoint on your server to have an email sent from your domain whenever needed. Here are some reasons you should enable custom-domain emails: * UserKit emails such as password-reset, registration, invites, will be sent from your own no-reply@yourdomain.com email address. By default emails are sent from UserKit's own email address. * Email links such as for password-reset and invites can send users to your own domain using the `widget_url` on your UserKit settings page (for example https://<yourdomain>.com/account). Without custom-domain email, links will always send your users to UserKit's own hosted widget page instead. * The send-invite feature will be enabled allowing you to send an invite with a single line of code. This feature is only enabled for apps with custom-domain email setup.
We recommend having emails sent from your own domain (for example no-reply@yourdomain.com). Once you have enabled custom-domain emails, UserKit will be able to make requests to an endpoint on your server to have an email sent from your domain whenever needed. Here are some reasons you should enable custom-domain emails: * UserKit emails such as password-reset, registration, invites, will be sent from your own no-reply@yourdomain.com email address. By default emails are sent from UserKit's own email address. * Email links such as for password-reset and invites can send users to your own domain using the `widget_url` on your UserKit settings page (for example https://<yourdomain>.com/account). Without custom-domain email, links will always send your users to UserKit's own hosted widget page instead. * The send-invite feature will be enabled allowing you to send an invite with a single line of code. This feature is only enabled for apps with custom-domain email setup.
{"_id":"581915998936870f0022efdd","__v":0,"api":{"settings":"","auth":"required","params":[],"url":"","results":{"codes":[{"name":"","status":200,"language":"json","code":"{}"},{"language":"json","code":"{}","name":"","status":400}]}},"githubsync":"","hidden":false,"parentDoc":null,"slug":"quickstart-sending-emails-from-custom-domain","category":"5819154bf62fee0f00949855","sync_unique":"","title":"Quickstart - Sending emails from custom domain","createdAt":"2016-11-01T22:22:17.236Z","link_external":false,"next":{"pages":[],"description":""},"project":"5589ceae9883a40d00c433f3","type":"basic","updates":[],"body":"In this quickstart you'll create an endpoint on your web server at `<yourdomain>.com/email_webhook`. When you're finished UserKit will be able to make requests to your server at that endpoint whenever it needs to have an email sent out.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"1. Create a webhook endpoint on your server\"\n}\n[/block]\nOn your server, create an endpoint for the following url: `/email_webhook`. Whenever UserKit needs to send an email it will make a POST request to that endpoint containing the following JSON in the request body:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n\\t\\\"email_key\\\": \\\"eml_MgXuRwRr0hIX-JSHgzKetRJGOv5qB5\\\"\\n}\",\n      \"language\": \"json\",\n      \"name\": null\n    }\n  ]\n}\n[/block]\nIn this example we'll be using [mailgun](https://www.mailgun.com) to send the email. Here's a function which handles requests to the `/email_webhook` endpoint. It get's the email data using the `email_key` UserKit sends in the request body:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"import json\\nimport requests\\nimport userkit\\n\\nuk = userkit.UserKit(\\\"<YOUR_APP_SECRET_KEY>\\\")\\n\\n\\n# This function handles requests to /email_webhook\\ndef email_handler(request, response):\\n  json_body = json.loads(request.body)\\n  email_key = json_body['email_key']\\n  \\n  # Fetch the actual email data UserKit wants to have sent\\n  email = uk.emails.get_pending_email(email_key)\\n  if not email:\\n    # Something is wrong with the email (it may have been sent\\n    # already, or this may be a malicious request). Abort.\\n    response.set_status(400)\\n    return\\n\\n  # Send the email\\n  resp = send_email(email)\\n  \\n  if resp.status_code == 200:\\n    # Notify UserKit that everything went well\\n    response.set_status(200)\\n  else:\\n    # Something went wrong\\n    response.set_status(500)\\n\\n    \\ndef send_email(email):\\n  # Send the email using MailGun. Remember to replace\\n  # <YOUR_EMAIL_DOMAIN_NAME>, <YOUR_MAILGUN_API_KEY> and\\n  # <YOUR_EMAIL@YOUR_DOMAIN.COM>\\n  return requests.post(\\n    'https://api.mailgun.net/v3/<YOUR_EMAIL_DOMAIN_NAME>/messages',\\n    auth=('api', '<YOUR_MAILGUN_API_KEY>'),\\n    data={'from': '<YOUR_EMAIL@YOUR_DOMAIN.COM>,\\n      \\t\\t'to': email.to,\\n      \\t\\t'subject': email.subject,\\n      \\t\\t'text': email.body})\",\n      \"language\": \"python\"\n    },\n    {\n      \"code\": \"<?php\\n\\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\\n\\n// Portions of following snippet are pseudo code\\n// This function handles requests to /email_webhook\\nfunction email_handler($request, $response)\\n{\\n  global $uk;\\n\\n  // convert the body response to a json array type \\n  $json_body = json_decode($response->body, true);\\n\\n  $email_key = $json_body['email_key'];\\n  \\n  // Fetch the actual email data UserKit wants to have sent\\n  $email = $uk->emails->getPendingEmail($email_key);\\n  if (!$email)\\n  {\\n    // Something is wrong with the email (it may have been sent\\n    // already, or this may be a malicious request). Abort.\\n    $response->set_status(400);\\n    return;\\n  }\\n  \\n  // Send the email\\n  $resp = send_email($email);\\n  \\n  if($resp->status_code == 200)\\n  {\\n    // Notify UserKit that everything went well\\n    $response->set_status(200);\\n  }\\n  else\\n  {\\n    // Something went wrong\\n    $response->set_status(500);\\n  }\\n}\\n\\nfunction send_mail($email)\\n{\\n  // Send the email using MailGun. Remember to replace\\n  // <YOUR_EMAIL_DOMAIN_NAME>, <YOUR_MAILGUN_API_KEY> and\\n  // <YOUR_EMAIL@YOUR_DOMAIN.COM>\\n\\n  $ch = curl_init();\\n  curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\\n  curl_setopt($ch, CURLOPT_USERPWD, 'api:' . <YOUR_MAILGUN_API_KEY>);\\n  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\\n  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');\\n  curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v2/' . <YOUR_EMAIL_DOMAIN_NAME> .'/messages');\\n  curl_setopt($ch, CURLOPT_POSTFIELDS, array(\\n    'from' => 'Open ' . '<YOUR_EMAIL@YOUR_DOMAIN.COM>',\\n    'to' => $email,\\n    'subject' => $email->subject,\\n    'html' => $email->body\\n  ));\\n\\n  $result = curl_exec($ch);\\n  curl_close($ch);\\n  return $result;\\n}\\n\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"2. Tell UserKit where your email endpoint is\"\n}\n[/block]\nIn the UserKit [dashboard](https://dashboard.userkit.io) select your app, then go to *settings* and in *Email webhook* enter the full URL to the endpoint you created in step 1. For example, https://<yourdomain>.com/email_webhook.","excerpt":"How to have UserKit send emails from your own domain","isReference":true,"link_url":"","order":1,"user":"5542d87d795b590d001dc7ff","version":"5589ceae9883a40d00c433f6","childrenPages":[]}

Quickstart - Sending emails from custom domain

How to have UserKit send emails from your own domain

In this quickstart you'll create an endpoint on your web server at `<yourdomain>.com/email_webhook`. When you're finished UserKit will be able to make requests to your server at that endpoint whenever it needs to have an email sent out. [block:api-header] { "type": "basic", "title": "1. Create a webhook endpoint on your server" } [/block] On your server, create an endpoint for the following url: `/email_webhook`. Whenever UserKit needs to send an email it will make a POST request to that endpoint containing the following JSON in the request body: [block:code] { "codes": [ { "code": "{\n\t\"email_key\": \"eml_MgXuRwRr0hIX-JSHgzKetRJGOv5qB5\"\n}", "language": "json", "name": null } ] } [/block] In this example we'll be using [mailgun](https://www.mailgun.com) to send the email. Here's a function which handles requests to the `/email_webhook` endpoint. It get's the email data using the `email_key` UserKit sends in the request body: [block:code] { "codes": [ { "code": "import json\nimport requests\nimport userkit\n\nuk = userkit.UserKit(\"<YOUR_APP_SECRET_KEY>\")\n\n\n# This function handles requests to /email_webhook\ndef email_handler(request, response):\n json_body = json.loads(request.body)\n email_key = json_body['email_key']\n \n # Fetch the actual email data UserKit wants to have sent\n email = uk.emails.get_pending_email(email_key)\n if not email:\n # Something is wrong with the email (it may have been sent\n # already, or this may be a malicious request). Abort.\n response.set_status(400)\n return\n\n # Send the email\n resp = send_email(email)\n \n if resp.status_code == 200:\n # Notify UserKit that everything went well\n response.set_status(200)\n else:\n # Something went wrong\n response.set_status(500)\n\n \ndef send_email(email):\n # Send the email using MailGun. Remember to replace\n # <YOUR_EMAIL_DOMAIN_NAME>, <YOUR_MAILGUN_API_KEY> and\n # <YOUR_EMAIL@YOUR_DOMAIN.COM>\n return requests.post(\n 'https://api.mailgun.net/v3/<YOUR_EMAIL_DOMAIN_NAME>/messages',\n auth=('api', '<YOUR_MAILGUN_API_KEY>'),\n data={'from': '<YOUR_EMAIL@YOUR_DOMAIN.COM>,\n \t\t'to': email.to,\n \t\t'subject': email.subject,\n \t\t'text': email.body})", "language": "python" }, { "code": "<?php\n\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\n// Portions of following snippet are pseudo code\n// This function handles requests to /email_webhook\nfunction email_handler($request, $response)\n{\n global $uk;\n\n // convert the body response to a json array type \n $json_body = json_decode($response->body, true);\n\n $email_key = $json_body['email_key'];\n \n // Fetch the actual email data UserKit wants to have sent\n $email = $uk->emails->getPendingEmail($email_key);\n if (!$email)\n {\n // Something is wrong with the email (it may have been sent\n // already, or this may be a malicious request). Abort.\n $response->set_status(400);\n return;\n }\n \n // Send the email\n $resp = send_email($email);\n \n if($resp->status_code == 200)\n {\n // Notify UserKit that everything went well\n $response->set_status(200);\n }\n else\n {\n // Something went wrong\n $response->set_status(500);\n }\n}\n\nfunction send_mail($email)\n{\n // Send the email using MailGun. Remember to replace\n // <YOUR_EMAIL_DOMAIN_NAME>, <YOUR_MAILGUN_API_KEY> and\n // <YOUR_EMAIL@YOUR_DOMAIN.COM>\n\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\n curl_setopt($ch, CURLOPT_USERPWD, 'api:' . <YOUR_MAILGUN_API_KEY>);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');\n curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v2/' . <YOUR_EMAIL_DOMAIN_NAME> .'/messages');\n curl_setopt($ch, CURLOPT_POSTFIELDS, array(\n 'from' => 'Open ' . '<YOUR_EMAIL@YOUR_DOMAIN.COM>',\n 'to' => $email,\n 'subject' => $email->subject,\n 'html' => $email->body\n ));\n\n $result = curl_exec($ch);\n curl_close($ch);\n return $result;\n}\n", "language": "php" } ] } [/block] [block:api-header] { "type": "basic", "title": "2. Tell UserKit where your email endpoint is" } [/block] In the UserKit [dashboard](https://dashboard.userkit.io) select your app, then go to *settings* and in *Email webhook* enter the full URL to the endpoint you created in step 1. For example, https://<yourdomain>.com/email_webhook.
In this quickstart you'll create an endpoint on your web server at `<yourdomain>.com/email_webhook`. When you're finished UserKit will be able to make requests to your server at that endpoint whenever it needs to have an email sent out. [block:api-header] { "type": "basic", "title": "1. Create a webhook endpoint on your server" } [/block] On your server, create an endpoint for the following url: `/email_webhook`. Whenever UserKit needs to send an email it will make a POST request to that endpoint containing the following JSON in the request body: [block:code] { "codes": [ { "code": "{\n\t\"email_key\": \"eml_MgXuRwRr0hIX-JSHgzKetRJGOv5qB5\"\n}", "language": "json", "name": null } ] } [/block] In this example we'll be using [mailgun](https://www.mailgun.com) to send the email. Here's a function which handles requests to the `/email_webhook` endpoint. It get's the email data using the `email_key` UserKit sends in the request body: [block:code] { "codes": [ { "code": "import json\nimport requests\nimport userkit\n\nuk = userkit.UserKit(\"<YOUR_APP_SECRET_KEY>\")\n\n\n# This function handles requests to /email_webhook\ndef email_handler(request, response):\n json_body = json.loads(request.body)\n email_key = json_body['email_key']\n \n # Fetch the actual email data UserKit wants to have sent\n email = uk.emails.get_pending_email(email_key)\n if not email:\n # Something is wrong with the email (it may have been sent\n # already, or this may be a malicious request). Abort.\n response.set_status(400)\n return\n\n # Send the email\n resp = send_email(email)\n \n if resp.status_code == 200:\n # Notify UserKit that everything went well\n response.set_status(200)\n else:\n # Something went wrong\n response.set_status(500)\n\n \ndef send_email(email):\n # Send the email using MailGun. Remember to replace\n # <YOUR_EMAIL_DOMAIN_NAME>, <YOUR_MAILGUN_API_KEY> and\n # <YOUR_EMAIL@YOUR_DOMAIN.COM>\n return requests.post(\n 'https://api.mailgun.net/v3/<YOUR_EMAIL_DOMAIN_NAME>/messages',\n auth=('api', '<YOUR_MAILGUN_API_KEY>'),\n data={'from': '<YOUR_EMAIL@YOUR_DOMAIN.COM>,\n \t\t'to': email.to,\n \t\t'subject': email.subject,\n \t\t'text': email.body})", "language": "python" }, { "code": "<?php\n\n$uk = new UserKit('<YOUR_APP_SECRET_KEY>');\n\n// Portions of following snippet are pseudo code\n// This function handles requests to /email_webhook\nfunction email_handler($request, $response)\n{\n global $uk;\n\n // convert the body response to a json array type \n $json_body = json_decode($response->body, true);\n\n $email_key = $json_body['email_key'];\n \n // Fetch the actual email data UserKit wants to have sent\n $email = $uk->emails->getPendingEmail($email_key);\n if (!$email)\n {\n // Something is wrong with the email (it may have been sent\n // already, or this may be a malicious request). Abort.\n $response->set_status(400);\n return;\n }\n \n // Send the email\n $resp = send_email($email);\n \n if($resp->status_code == 200)\n {\n // Notify UserKit that everything went well\n $response->set_status(200);\n }\n else\n {\n // Something went wrong\n $response->set_status(500);\n }\n}\n\nfunction send_mail($email)\n{\n // Send the email using MailGun. Remember to replace\n // <YOUR_EMAIL_DOMAIN_NAME>, <YOUR_MAILGUN_API_KEY> and\n // <YOUR_EMAIL@YOUR_DOMAIN.COM>\n\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\n curl_setopt($ch, CURLOPT_USERPWD, 'api:' . <YOUR_MAILGUN_API_KEY>);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');\n curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v2/' . <YOUR_EMAIL_DOMAIN_NAME> .'/messages');\n curl_setopt($ch, CURLOPT_POSTFIELDS, array(\n 'from' => 'Open ' . '<YOUR_EMAIL@YOUR_DOMAIN.COM>',\n 'to' => $email,\n 'subject' => $email->subject,\n 'html' => $email->body\n ));\n\n $result = curl_exec($ch);\n curl_close($ch);\n return $result;\n}\n", "language": "php" } ] } [/block] [block:api-header] { "type": "basic", "title": "2. Tell UserKit where your email endpoint is" } [/block] In the UserKit [dashboard](https://dashboard.userkit.io) select your app, then go to *settings* and in *Email webhook* enter the full URL to the endpoint you created in step 1. For example, https://<yourdomain>.com/email_webhook.
{"_id":"58a350973dfce00f00e37912","order":0,"user":"555297897e64980d008d3baf","__v":0,"category":"589e29c72793e937001c15c5","excerpt":"Mitigating the Most Common XSS attack using HttpOnly","next":{"pages":[],"description":""},"type":"basic","createdAt":"2017-02-14T18:46:47.746Z","link_url":"","sync_unique":"","title":"Overview - Http-only cookies","project":"5589ceae9883a40d00c433f3","slug":"overview-http-only-cookies","version":"5589ceae9883a40d00c433f6","api":{"results":{"codes":[{"status":200,"language":"json","code":"{}","name":""},{"language":"json","code":"{}","name":"","status":400}]},"settings":"","auth":"required","params":[],"url":""},"body":"Using the HttpOnly flag when generating a cookie helps mitigate the risk of client side script accessing the protected cookie (if the browser supports it). To enable http-only session cookies on your website, you'll need to follow some simple setup instructions:\n\n- Set up a server-side endpoint that uses the UserKit SDK to forward requests from the widget to UserKit servers and sets an HTTP-only cookie on the response\n- Configure the UserKit widget to send requests to your endpoint","hidden":false,"updates":[],"githubsync":"","isReference":false,"link_external":false,"parentDoc":null,"childrenPages":[]}

Overview - Http-only cookies

Mitigating the Most Common XSS attack using HttpOnly

Using the HttpOnly flag when generating a cookie helps mitigate the risk of client side script accessing the protected cookie (if the browser supports it). To enable http-only session cookies on your website, you'll need to follow some simple setup instructions: - Set up a server-side endpoint that uses the UserKit SDK to forward requests from the widget to UserKit servers and sets an HTTP-only cookie on the response - Configure the UserKit widget to send requests to your endpoint
Using the HttpOnly flag when generating a cookie helps mitigate the risk of client side script accessing the protected cookie (if the browser supports it). To enable http-only session cookies on your website, you'll need to follow some simple setup instructions: - Set up a server-side endpoint that uses the UserKit SDK to forward requests from the widget to UserKit servers and sets an HTTP-only cookie on the response - Configure the UserKit widget to send requests to your endpoint
{"_id":"589e2a392793e937001c15c6","parentDoc":null,"sync_unique":"","__v":0,"createdAt":"2017-02-10T21:01:45.254Z","link_external":false,"isReference":false,"title":"Setup UserKit with HTTP-only cookies","updates":[],"version":"5589ceae9883a40d00c433f6","body":"[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"1. Setup a proxy endpoint\"\n}\n[/block]\nTo enable http-only session cookies on your website, you'll need to setup an endpoint on your website that will forward requests from the widget to UserKit servers.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"import userkit\\nuk = userkit.UserKit('{YOUR_USERKIT_SECRET_KEY}')\\n\\n\\n# Handler for /userkit-widget-proxy endpoint\\ndef widget_proxy_handler(request, response):\\n  # 1. Extract the private token from the http-only cookie.\\n  # 2. Forward the UserKit widget request to UserKit's servers,\\n  #    along with the private token.\\n  # 3. Set the http-only cookie.\\n  # 4. Return the UserKit response back to the widget.\\n  private_token = request.cookies.get('httponly_session_token')\\n  resp = uk.widget.proxy(request.data, private_token)\\n  response.set_cookie('httponly_session_token', resp.token_private,\\n                      httponly=True)\\n  response.write(resp.body)\",\n      \"language\": \"python\"\n    },\n    {\n      \"code\": \"from flask import Flask, request, make_response\\napp = Flask(__name__)\\nimport userkit\\nuk = userkit.UserKit('{YOUR_USERKIT_SECRET_KEY}')\\n\\n\\n@app.route('/userkit-widget-proxy')\\ndef userkit_widget_proxy():\\n  # 1. Extract the private token from the http-only cookie.\\n  # 2. Forward the UserKit widget request to UserKit's servers,\\n  #    along with the private token.\\n  # 3. Set the http-only cookie.\\n  # 4. Return the UserKit response back to the widget.\\n  private_token = request.cookies.get('httponly_session_token')\\n  resp = uk.widget.proxy(request.data, private_token)\\n  response = make_response(resp.response)\\n  response.set_cookie('httponly_session_token', resp.token_private,\\n                      httponly=True)\\n  return response\",\n      \"language\": \"python\",\n      \"name\": \"Python (Flask)\"\n    },\n    {\n      \"code\": \"import webapp2\\nimport userkit\\nuk = userkit.UserKit('{YOUR_USERKIT_SECRET_KEY}')\\n\\n\\n# Handler for /userkit-widget-proxy endpoint\\nclass UserKitWidgetProxy(webapp2.RequestHandler):\\n  \\n  def post(self):\\n    # 1. Extract the private token from the http-only cookie.\\n    # 2. Forward the UserKit widget request to UserKit's servers,\\n    #    along with the private token.\\n    # 3. Set the http-only cookie.\\n    # 4. Return the UserKit response back to the widget.\\n    private_token = self.request.cookies.get('httponly_session_token')\\n    resp = uk.widget.proxy(self.request.body, private_token)\\n    self.response.set_cookie('httponly_session_token',\\n                             resp.private_token,\\n                             httponly=True)\\n    self.response.write(resp.response)\",\n      \"language\": \"python\",\n      \"name\": \"Python (App Engine)\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"2. Configure the UserKit widget\"\n}\n[/block]\nNext you'll need to tell the UserKit widget that it should make requests to the endpoint you setup in step 1. Do this by setting the `data-proxy` data property:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<script src=\\\"https://widget.userkit.io/widget.js\\\"\\n\\tdata-proxy=\\\"/userkit-widget-proxy\\\">\\n</script>\",\n      \"language\": \"html\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"3. Getting a user server-side with the http-only token\"\n}\n[/block]\nWhen you want to fetch a user via the server SDK, you'll need to pass the http-only token along with the usual session token.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"import userkit\\nuk = userkit.UserKit(\\\"<YOUR_APP_SECRET_KEY>\\\")\\n\\n\\ndef request_handler(request, response):\\n  # Along with the usual session token, you'll also need\\n  # to pass in the private token from the httponly cookie\\n  # you set in your widget proxy endpoint\\n  token = request.get_cookie(\\\"userkit_auth_token\\\")\\n  httponly_token = request.get_cookie(\\\"httponly_session_token\\\")\\n  user = uk.users.get_current_user(token, httponly_token)\\n  \\n  if user:\\n    # There's a logged in user\\n    response.write(\\\"Welcome, {}\\\".format(user.name))\\n  else:\\n    # No logged in user, redirect to login page\\n    response.redirect(\\\"/account.html\\\")\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]","category":"589e29c72793e937001c15c5","hidden":false,"type":"basic","next":{"pages":[],"description":""},"project":"5589ceae9883a40d00c433f3","slug":"setup-userkit-with-http-only-cookies","githubsync":"","link_url":"","order":1,"user":"5542d87d795b590d001dc7ff","api":{"results":{"codes":[{"language":"json","code":"{}","name":"","status":200},{"status":400,"language":"json","code":"{}","name":""}]},"settings":"","auth":"required","params":[],"url":""},"excerpt":"","childrenPages":[]}

Setup UserKit with HTTP-only cookies


[block:api-header] { "type": "basic", "title": "1. Setup a proxy endpoint" } [/block] To enable http-only session cookies on your website, you'll need to setup an endpoint on your website that will forward requests from the widget to UserKit servers. [block:code] { "codes": [ { "code": "import userkit\nuk = userkit.UserKit('{YOUR_USERKIT_SECRET_KEY}')\n\n\n# Handler for /userkit-widget-proxy endpoint\ndef widget_proxy_handler(request, response):\n # 1. Extract the private token from the http-only cookie.\n # 2. Forward the UserKit widget request to UserKit's servers,\n # along with the private token.\n # 3. Set the http-only cookie.\n # 4. Return the UserKit response back to the widget.\n private_token = request.cookies.get('httponly_session_token')\n resp = uk.widget.proxy(request.data, private_token)\n response.set_cookie('httponly_session_token', resp.token_private,\n httponly=True)\n response.write(resp.body)", "language": "python" }, { "code": "from flask import Flask, request, make_response\napp = Flask(__name__)\nimport userkit\nuk = userkit.UserKit('{YOUR_USERKIT_SECRET_KEY}')\n\n\n@app.route('/userkit-widget-proxy')\ndef userkit_widget_proxy():\n # 1. Extract the private token from the http-only cookie.\n # 2. Forward the UserKit widget request to UserKit's servers,\n # along with the private token.\n # 3. Set the http-only cookie.\n # 4. Return the UserKit response back to the widget.\n private_token = request.cookies.get('httponly_session_token')\n resp = uk.widget.proxy(request.data, private_token)\n response = make_response(resp.response)\n response.set_cookie('httponly_session_token', resp.token_private,\n httponly=True)\n return response", "language": "python", "name": "Python (Flask)" }, { "code": "import webapp2\nimport userkit\nuk = userkit.UserKit('{YOUR_USERKIT_SECRET_KEY}')\n\n\n# Handler for /userkit-widget-proxy endpoint\nclass UserKitWidgetProxy(webapp2.RequestHandler):\n \n def post(self):\n # 1. Extract the private token from the http-only cookie.\n # 2. Forward the UserKit widget request to UserKit's servers,\n # along with the private token.\n # 3. Set the http-only cookie.\n # 4. Return the UserKit response back to the widget.\n private_token = self.request.cookies.get('httponly_session_token')\n resp = uk.widget.proxy(self.request.body, private_token)\n self.response.set_cookie('httponly_session_token',\n resp.private_token,\n httponly=True)\n self.response.write(resp.response)", "language": "python", "name": "Python (App Engine)" } ] } [/block] [block:api-header] { "type": "basic", "title": "2. Configure the UserKit widget" } [/block] Next you'll need to tell the UserKit widget that it should make requests to the endpoint you setup in step 1. Do this by setting the `data-proxy` data property: [block:code] { "codes": [ { "code": "<script src=\"https://widget.userkit.io/widget.js\"\n\tdata-proxy=\"/userkit-widget-proxy\">\n</script>", "language": "html" } ] } [/block] [block:api-header] { "type": "basic", "title": "3. Getting a user server-side with the http-only token" } [/block] When you want to fetch a user via the server SDK, you'll need to pass the http-only token along with the usual session token. [block:code] { "codes": [ { "code": "import userkit\nuk = userkit.UserKit(\"<YOUR_APP_SECRET_KEY>\")\n\n\ndef request_handler(request, response):\n # Along with the usual session token, you'll also need\n # to pass in the private token from the httponly cookie\n # you set in your widget proxy endpoint\n token = request.get_cookie(\"userkit_auth_token\")\n httponly_token = request.get_cookie(\"httponly_session_token\")\n user = uk.users.get_current_user(token, httponly_token)\n \n if user:\n # There's a logged in user\n response.write(\"Welcome, {}\".format(user.name))\n else:\n # No logged in user, redirect to login page\n response.redirect(\"/account.html\")", "language": "python" } ] } [/block]
[block:api-header] { "type": "basic", "title": "1. Setup a proxy endpoint" } [/block] To enable http-only session cookies on your website, you'll need to setup an endpoint on your website that will forward requests from the widget to UserKit servers. [block:code] { "codes": [ { "code": "import userkit\nuk = userkit.UserKit('{YOUR_USERKIT_SECRET_KEY}')\n\n\n# Handler for /userkit-widget-proxy endpoint\ndef widget_proxy_handler(request, response):\n # 1. Extract the private token from the http-only cookie.\n # 2. Forward the UserKit widget request to UserKit's servers,\n # along with the private token.\n # 3. Set the http-only cookie.\n # 4. Return the UserKit response back to the widget.\n private_token = request.cookies.get('httponly_session_token')\n resp = uk.widget.proxy(request.data, private_token)\n response.set_cookie('httponly_session_token', resp.token_private,\n httponly=True)\n response.write(resp.body)", "language": "python" }, { "code": "from flask import Flask, request, make_response\napp = Flask(__name__)\nimport userkit\nuk = userkit.UserKit('{YOUR_USERKIT_SECRET_KEY}')\n\n\n@app.route('/userkit-widget-proxy')\ndef userkit_widget_proxy():\n # 1. Extract the private token from the http-only cookie.\n # 2. Forward the UserKit widget request to UserKit's servers,\n # along with the private token.\n # 3. Set the http-only cookie.\n # 4. Return the UserKit response back to the widget.\n private_token = request.cookies.get('httponly_session_token')\n resp = uk.widget.proxy(request.data, private_token)\n response = make_response(resp.response)\n response.set_cookie('httponly_session_token', resp.token_private,\n httponly=True)\n return response", "language": "python", "name": "Python (Flask)" }, { "code": "import webapp2\nimport userkit\nuk = userkit.UserKit('{YOUR_USERKIT_SECRET_KEY}')\n\n\n# Handler for /userkit-widget-proxy endpoint\nclass UserKitWidgetProxy(webapp2.RequestHandler):\n \n def post(self):\n # 1. Extract the private token from the http-only cookie.\n # 2. Forward the UserKit widget request to UserKit's servers,\n # along with the private token.\n # 3. Set the http-only cookie.\n # 4. Return the UserKit response back to the widget.\n private_token = self.request.cookies.get('httponly_session_token')\n resp = uk.widget.proxy(self.request.body, private_token)\n self.response.set_cookie('httponly_session_token',\n resp.private_token,\n httponly=True)\n self.response.write(resp.response)", "language": "python", "name": "Python (App Engine)" } ] } [/block] [block:api-header] { "type": "basic", "title": "2. Configure the UserKit widget" } [/block] Next you'll need to tell the UserKit widget that it should make requests to the endpoint you setup in step 1. Do this by setting the `data-proxy` data property: [block:code] { "codes": [ { "code": "<script src=\"https://widget.userkit.io/widget.js\"\n\tdata-proxy=\"/userkit-widget-proxy\">\n</script>", "language": "html" } ] } [/block] [block:api-header] { "type": "basic", "title": "3. Getting a user server-side with the http-only token" } [/block] When you want to fetch a user via the server SDK, you'll need to pass the http-only token along with the usual session token. [block:code] { "codes": [ { "code": "import userkit\nuk = userkit.UserKit(\"<YOUR_APP_SECRET_KEY>\")\n\n\ndef request_handler(request, response):\n # Along with the usual session token, you'll also need\n # to pass in the private token from the httponly cookie\n # you set in your widget proxy endpoint\n token = request.get_cookie(\"userkit_auth_token\")\n httponly_token = request.get_cookie(\"httponly_session_token\")\n user = uk.users.get_current_user(token, httponly_token)\n \n if user:\n # There's a logged in user\n response.write(\"Welcome, {}\".format(user.name))\n else:\n # No logged in user, redirect to login page\n response.redirect(\"/account.html\")", "language": "python" } ] } [/block]