{"id":13684096,"url":"https://github.com/ADmad/cakephp-social-auth","last_synced_at":"2025-04-30T20:33:02.950Z","repository":{"id":20327434,"uuid":"88990997","full_name":"ADmad/cakephp-social-auth","owner":"ADmad","description":"A CakePHP plugin which allows you to authenticate using social providers like Facebook/Google/Twitter.","archived":false,"fork":false,"pushed_at":"2024-06-25T19:12:10.000Z","size":131,"stargazers_count":51,"open_issues_count":5,"forks_count":23,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-07T07:16:12.364Z","etag":null,"topics":["cakephp-plugin","middleware","oauth2","php","social-providers"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ADmad.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["ADmad"]}},"created_at":"2017-04-21T14:14:47.000Z","updated_at":"2025-02-25T22:55:14.000Z","dependencies_parsed_at":"2024-04-10T02:56:10.633Z","dependency_job_id":"8569170f-3e64-45f3-a06d-8998cf63743e","html_url":"https://github.com/ADmad/cakephp-social-auth","commit_stats":{"total_commits":138,"total_committers":10,"mean_commits":13.8,"dds":"0.23913043478260865","last_synced_commit":"95343c78ef521402245a94104717c7ca84fa5e6f"},"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ADmad%2Fcakephp-social-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ADmad%2Fcakephp-social-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ADmad%2Fcakephp-social-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ADmad%2Fcakephp-social-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ADmad","download_url":"https://codeload.github.com/ADmad/cakephp-social-auth/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251777703,"owners_count":21642212,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cakephp-plugin","middleware","oauth2","php","social-providers"],"created_at":"2024-08-02T14:00:25.658Z","updated_at":"2025-04-30T20:33:02.940Z","avatar_url":"https://github.com/ADmad.png","language":"PHP","funding_links":["https://github.com/sponsors/ADmad"],"categories":["Authentication and Authorization","Plugins"],"sub_categories":["Authentication and Authorization"],"readme":"# CakePHP SocialAuth Plugin\n\n[![Total Downloads](https://img.shields.io/packagist/dt/ADmad/cakephp-social-auth.svg?style=flat-square)](https://packagist.org/packages/admad/cakephp-social-auth)\n[![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](LICENSE)\n\nA CakePHP plugin which allows you authenticate using social providers like\nFacebook/Google/Twitter etc. using [SocialConnect/auth](https://github.com/SocialConnect/auth)\nsocial sign on library.\n\n## Installation\n\nRun:\n\n```\ncomposer require admad/cakephp-social-auth\n```\n\n## Setup\n\nLoad the plugin by running following command in terminal:\n\n```\nbin/cake plugin load ADmad/SocialAuth\n```\n\n## Database\n\nThis plugin requires a migration to generate a `social_profiles` table, and it\ncan be generated via the official Migrations plugin as follows:\n\n```shell\nbin/cake migrations migrate -p ADmad/SocialAuth\n```\n\n## Usage\n\n### Middleware config\n\nThe plugin provides a `\\ADmad\\SocialAuth\\Middleware\\SocialAuthMiddleware` which\nhandles authentication process through social providers.\n\nYou can configure the middleware in your `Application::middleware()` method as shown:\n\n```php\n// src/Application.php\n\n// Be sure to add SocialAuthMiddleware after RoutingMiddleware\n$middlewareQueue-\u003eadd(new \\ADmad\\SocialAuth\\Middleware\\SocialAuthMiddleware([\n    // Request method type use to initiate authentication.\n    'requestMethod' =\u003e 'POST',\n    // Login page URL. In case of auth failure user is redirected to login\n    // page with \"error\" query string var.\n    'loginUrl' =\u003e '/users/login',\n    // URL to redirect to after authentication (string or array).\n    'loginRedirect' =\u003e '/',\n    // Boolean indicating whether user identity should be returned as entity.\n    'userEntity' =\u003e false,\n    // User model.\n    'userModel' =\u003e 'Users',\n    // Social profile model.\n    'socialProfileModel' =\u003e 'ADmad/SocialAuth.SocialProfiles',\n    // Finder type.\n    'finder' =\u003e 'all',\n    // Fields.\n    'fields' =\u003e [\n        'password' =\u003e 'password',\n    ],\n    // Session key to which to write identity record to.\n    'sessionKey' =\u003e 'Auth',\n    // The method in user model which should be called in case of new user.\n    // It should return a User entity.\n    'getUserCallback' =\u003e 'getUser',\n    // SocialConnect Auth service's providers config. https://github.com/SocialConnect/auth/blob/master/README.md\n    'serviceConfig' =\u003e [\n        'provider' =\u003e [\n            'facebook' =\u003e [\n                'applicationId' =\u003e '\u003capplication id\u003e',\n                'applicationSecret' =\u003e '\u003capplication secret\u003e',\n                'scope' =\u003e [\n                    'email',\n                ],\n                'options' =\u003e [\n                    'identity.fields' =\u003e [\n                        'email',\n                        // To get a full list of all possible values, refer to\n                        // https://developers.facebook.com/docs/graph-api/reference/user\n                    ],\n                ],\n            ],\n            'google' =\u003e [\n                'applicationId' =\u003e '\u003capplication id\u003e',\n                'applicationSecret' =\u003e '\u003capplication secret\u003e',\n                'scope' =\u003e [\n                    'https://www.googleapis.com/auth/userinfo.email',\n                    'https://www.googleapis.com/auth/userinfo.profile',\n                ],\n            ],\n        ],\n    ],\n    // Instance of `\\SocialConnect\\Auth\\CollectionFactory`. If none provided one will be auto created. Default `null`.\n    'collectionFactory' =\u003e null,\n    // Whether social connect errors should be logged. Default `true`.\n    'logErrors' =\u003e true,\n]));\n```\n\n### Login links\n\nOn your login page you can create links to initiate authentication using required\nproviders. E.g.\n\n```php\necho $this-\u003eForm-\u003epostLink(\n    'Login with Facebook',\n    [\n        'prefix' =\u003e false,\n        'plugin' =\u003e 'ADmad/SocialAuth',\n        'controller' =\u003e 'Auth',\n        'action' =\u003e 'login',\n        'provider' =\u003e 'facebook',\n        '?' =\u003e ['redirect' =\u003e $this-\u003erequest-\u003egetQuery('redirect')]\n    ]\n);\n```\n\nWe use a `POST` link here instead of a normal link to prevent search bots and other\ncrawlers from following the link. If you prefer using GET you can still do so by\nconfiguring the middleware with `'requestMethod' =\u003e 'GET'`. In this case it's\nadvisable to add `nofollow` attribute to the link.\n\n### Authentication process\n\nDepending on the provider name in the login URL the authentication process is\ninitiated.\n\nOnce a user is authenticated through the provider, the middleware gets the user\nprofile from the identity provider and using that tries to find the corresponding\nuser record using the user model. If no user is found it calls the `getUser` method\nof your user model. The method recieves social profile model entity and session\ninstance as argument and must return an entity for the user.\n\n```php\n// src/Model/Table/UsersTable.php\nuse \\Cake\\Datasource\\EntityInterface;\nuse \\Cake\\Http\\Session;\n\npublic function getUser(EntityInterface $profile, Session $session)\n{\n    // Make sure here that all the required fields are actually present\n    if (empty($profile-\u003eemail)) {\n        throw new \\RuntimeException('Could not find email in social profile.');\n    }\n\n    // If you want to associate the social entity with currently logged in user\n    // use the $session argument to get user id and find matching user entity.\n    $userId = $session-\u003eread('Auth.id');\n    if ($userId) {\n        return $this-\u003eget($userId);\n    }\n\n    // Check if user with same email exists. This avoids creating multiple\n    // user accounts for different social identities of same user. You should\n    // probably skip this check if your system doesn't enforce unique email\n    // per user.\n    $user = $this-\u003efind()\n        -\u003ewhere(['email' =\u003e $profile-\u003eemail])\n        -\u003efirst();\n\n    if ($user) {\n        return $user;\n    }\n\n    // Create new user account\n    $user = $this-\u003enewEntity(['email' =\u003e $profile-\u003eemail]);\n    $user = $this-\u003esave($user);\n\n    if (!$user) {\n        throw new \\RuntimeException('Unable to save new user');\n    }\n\n    return $user;\n}\n```\n\nInstead of adding a `getUser` method to your `UsersTable` you can also setup a\nlistener for the `SocialAuth.createUser` callback and return a `User` entity from\nthe listener callback, in a similar way as shown above.\n\nUpon successful authentication the user identity is persisted to the session\nunder the key you have specified in the middleware config (`Auth.User` by default).\n\nAfter that the user is redirected to protected page they tried to access before\nlogin or to the URL specified in `loginRedirect` config.\n\nIn case of authentication failure the user is redirected back to login URL.\n\n### Events\n\n#### SocialAuth.createUser\n\nAfter authentication from the social auth provider if a related use record is not\nfound then `SocialAuth.createUser` is triggered. As an alternative to adding a\nnew `createUser()` method in your `UsersTable` as mentioned above you can instead\nuse this event to return an entity for a new user.\n\n#### SocialAuth.afterIdentify\n\nUpon successful authentication a `SocialAuth.afterIdentify` event is\ndispatched with the user entity. You can setup a listener for this event to\nperform required tasks. The listener can optionally return a user entity as\nevent result.\n\n#### SocialAuth.beforeRedirect\n\nAfter the completion of authentication process before the user is redirected\nto required URL a `SocialAuth.beforeRedirect` event is triggered. This event\nfor e.g. can be used to set a visual notification like flash message to indicate\nthe result of the authentication process to the user.\n\nHere's an e.g. listener with callbacks to the above method:\n\n```php\n// src/Event/SocialAuthListener.php\n\nnamespace App\\Event;\n\nuse ADmad\\SocialAuth\\Middleware\\SocialAuthMiddleware;\nuse Cake\\Datasource\\EntityInterface;\nuse Cake\\Event\\EventInterface;\nuse Cake\\Event\\EventListenerInterface;\nuse Cake\\Http\\ServerRequest;\nuse Cake\\I18n\\FrozenTime;\nuse Cake\\ORM\\Locator\\LocatorAwareTrait;\n\nclass SocialAuthListener implements EventListenerInterface\n{\n    use LocatorAwareTrait;\n\n    public function implementedEvents(): array\n    {\n        return [\n            SocialAuthMiddleware::EVENT_AFTER_IDENTIFY =\u003e 'afterIdentify',\n            SocialAuthMiddleware::EVENT_BEFORE_REDIRECT =\u003e 'beforeRedirect',\n            // Uncomment below if you want to use the event listener to return\n            // an entity for a new user instead of directly using `createUser()` table method.\n            // SocialAuthMiddleware::EVENT_CREATE_USER =\u003e 'createUser',\n        ];\n    }\n\n    public function afterIdentify(EventInterface $event, EntityInterface $user): EntityInterface\n    {\n        // Update last login time\n        $user-\u003eset('last_login', new FrozenTime());\n\n        // You can access the profile using $user-\u003esocial_profile\n\n        $this-\u003egetTableLocator()-\u003eget('Users')-\u003esaveOrFail($user);\n\n        return $user;\n    }\n\n    /**\n     * @param \\Cake\\Event\\EventInterface $event\n     * @param string|array $url\n     * @param string $status\n     * @param \\Cake\\Http\\ServerRequest $request\n     * @return void\n     */\n    public function beforeRedirect(EventInterface $event, $url, string $status, ServerRequest $request): void\n    {\n        // Set flash message\n        switch ($status) {\n            case SocialAuthMiddleware::AUTH_STATUS_SUCCESS:\n                $request-\u003egetFlash()-\u003eerror('You are now logged in.');\n                break;\n\n            // Auth through provider failed. Details will be logged in\n            // `error.log` if `logErrors` option is set to `true`.\n            case SocialAuthMiddleware::AUTH_STATUS_PROVIDER_FAILURE:\n\n            // Table finder failed to return user record. An e.g. of this is a\n            // user has been authenticated through provider but your finder has\n            // a condition to not return an inactivated user.\n            case SocialAuthMiddleware::AUTH_STATUS_FINDER_FAILURE:\n                $request-\u003egetFlash()-\u003eerror('Authentication failed.');\n                break;\n\n            case SocialAuthMiddleware::AUTH_STATUS_IDENTITY_MISMATCH:\n                $request-\u003egetFlash()-\u003eerror('The social profile is already linked to another user.');\n                break;\n        }\n\n        // You can return a modified redirect URL if needed.\n    }\n\n    public function createUser(EventInterface $event, EntityInterface $profile, Session $session): EntityInterface\n    {\n        // Create and save entity for new user as shown in \"createUser()\" method above\n\n        return $user;\n    }\n}\n```\n\nAttach the listener in your `Application` class:\n\n```php\n// src/Application.php\nuse App\\Event\\SocialAuthListener;\nuse Cake\\Event\\EventManager;\n\n// In Application::bootstrap() or Application::middleware()\nEventManager::instance()-\u003eon(new SocialAuthListener());\n```\n\n### Extend with custom providers\n\nIn order to enable custom providers (those not pre-included with `SocialConnect/Auth`)\nyou can extend the middleware configuration with `collectionFactory` and passing in\nyour own instance of `SocialConnect\\Auth\\CollectionFactory`.\n\nFor e.g. create your custom provider at `src/Authenticator/MyProvider.php`.\nCheck the providers in `vendor/socialconnect/auth/src/(OAuth1|OAuth2|OpenIDConnect)/Provider/`\nfor examples.\n\nCreate an instance of `CollectionFactory`.\n\n```php\n$collectionFactory = new \\SocialConnect\\Auth\\CollectionFactory();\n$collectionFactory-\u003eregister(\\App\\Authenticator\\MyProvider::NAME, \\App\\Authenticator\\MyProvider::class);\n```\n\nThen set the factory instance in the middlware config shown above:\n```\n...\n'collectionFactory' =\u003e $collectionFactory\n...\n```\n\nCopyright\n---------\nCopyright 2017-Present ADmad\n\nLicense\n-------\n[See LICENSE](LICENSE.txt)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FADmad%2Fcakephp-social-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FADmad%2Fcakephp-social-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FADmad%2Fcakephp-social-auth/lists"}