# Wordpress auth

Add the following code to `wp-content/themes/bravada/functions.php`:

```
function rot_auth( $user, $username, $password ){
    // Make sure a username and password are present for us to work with
    if($username == '' || $password == '') return;

	$ch = curl_init();
	
	curl_setopt($ch, CURLOPT_URL, 'https://app.rudernlinz.at/wikiauth');
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, "name=$username&password=$password");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);	
	
	// Execute the cURL session and get the response
	$response = curl_exec($ch);
	
	// Check for cURL errors
	if(curl_errno($ch)){
        	$user = new WP_Error( 'denied', __('Curl error: ' . curl_error($ch)) );
	}
	
	// Close the cURL session
	curl_close($ch);


	if (strpos($response, 'SUCC') !== false) {
        	$user = get_user_by('login', $username);
        	
        	if (!$user) {
        	   // User does not exist, create a new one
        	   $userdata = array(
        	       'user_email' => $username,
        	       'user_login' => $username, 
        	       'first_name' => $username,
        	       'last_name' => ''
        	   );
        	   $new_user_id = wp_insert_user($userdata);

        	   if (!is_wp_error($new_user_id)) {
        	       // Load the new user info
        	       $user = new WP_User($new_user_id);
        	       
        	       // Set role based on username
        	       if ($username == 'Philipp Hofer' || $username == 'Marie Birner') {
        	           $user->set_role('administrator');
        	       } else {
        	           $user->set_role('editor');
        	       }
        	   } else {
        	       // Handle error in user creation
        	       return $new_user_id;
        	   }
        	} else {
        	}
	
	} else {
        	$user = new WP_Error( 'denied', __("Falscher Benutzername/Passwort. Verwendest du deine Accountdaten vom Ruderassistenten?") );
	}



     return $user;
}

// Comment this line if you wish to fall back on WordPress authentication
// Useful for times when the external service is offline
remove_action('authenticate', 'wp_authenticate_username_password', 20);

add_filter( 'authenticate', 'rot_auth', 10, 3 );
```
