SurrealDB Docs Logo

Enter a search query

Authentication

Since SurrealDB is a database that is designed to be used in a distributed environment, it is important to secure the database and the data that is stored in it. SurrealDB provides a number of methods for authenticating users and securing the database.

Define scope

If you haven’t defined a scope for your database, you can define a scope by quering to the database using the query method.

$db->query(' DEFINE SCOPE user SESSION 24h SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($pass) ) SIGNIN ( SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $pass) ); ');

In 2.0 and above, the DEFINE SCOPE Statement has been replaced with the DEFINE ACCESS ... TYPE RECORD Statement so the above query would be:

$db->query(' DEFINE ACCESS user ON DATABASE TYPE RECORD SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($pass) ) SIGNIN ( SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $pass) ) DURATION FOR TOKEN 15m, FOR SESSION 12h ; ');

Signup with credentials

To signup a new scoped user, you can use the signup method from the Surreal class. This method takes an associative array with the namespace, database, and scope keys as arguments. The email and pass keys are also required for this example, but it can be different depending on the required parameters you have defined for the scope.

$db->signup([ "namespace" => "surrealdb", "database" => "surrealdb", "scope" => "user", "email" => "user@email.com", "pass" => "password-123" ]);
// 2.0 and above $db->signup([ "namespace" => "surrealdb", "database" => "surrealdb", "access" => "user", "email" => "user@email.com", "pass" => "password-123" ]);

Signin with credentials

To signin with credentials, you can use the signin method.

Root authentication gives you access to all namespaces and databases within the SurrealDB instance.

$token = $db->signin([ "username" => "root", "password" => "root" ]);

Signin with auth token

If you already have signed in and have an auth token stored somewhere, you can authenticate using the authenticate method. This method takes one argument, the auth token.

$db->authenticate($token);

User information

When you signed in successfully, you can get the user information by using the info method. This returns the user information as an associative array.

$user = $db->info();

Invalidate user session

To invalidate a user session, you can use the invalidate method. When executed, the user session will be invalidated and the user will be signed out.

$db->invalidate();

In the next article we will cover how to query to the database.

© SurrealDB GitHub Discord Community Cloud Features Releases Install