Skip to content

Commit

Permalink
Merge pull request #2 from SurajShettigar/master
Browse files Browse the repository at this point in the history
Add user authorization. Add fetching of posts, comments, users. Update README.md
  • Loading branch information
SachinGanesh authored Feb 15, 2019
2 parents 63e80b6 + 3ea4dec commit 96c6b18
Show file tree
Hide file tree
Showing 21 changed files with 1,390 additions and 352 deletions.
355 changes: 209 additions & 146 deletions .idea/workspace.xml

Large diffs are not rendered by default.

93 changes: 88 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,93 @@
# flutter_wordpress
# Flutter Wordpress

Flutter Wordpress API
This library uses [WordPress REST API V2](https://developer.wordpress.org/rest-api/) to provide a way for your application to interact with your WordPress website.

## Requirements
- A Wordpress site using V2 REST API https://developer.wordpress.org/rest-api/
- JWT Authentication for WP REST API V2 https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/
- Flutter 1.0 https://flutter.io/docs/get-started/install
For authentication and usage of administrator level REST APIs, you need to use either of the two popular authentication plugins in your WordPress site:
1. [Application Passwords](https://wordpress.org/plugins/application-passwords/)
2. [JWT Authentication for WP REST API](https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/)

## Getting Started

### 1. Import library

```dart
import 'package:flutter_wordpress/flutter_wordpress.dart' as wp;
```

### 2. Instantiate WordPress class

```dart
wp.WordPress wordPress;
// adminName and adminKey is needed only for admin level APIs
wordPress = wp.WordPress(
baseUrl: 'http://localhost',
authenticator: wp.WordPressAuthenticator.ApplicationPasswords,
adminName: '',
adminKey: '',
);
```

### 3. Authenticate User

```dart
Future<wp.User> response = wordPress.authenticateUser(
username: 'username',
password: 'password',
);
response.then((user) {
print(user.toString());
}).catchError((err) {
print(err.toString());
});
```

### 4. Fetch Posts

```dart
Future<List<wp.Post>> posts = wordPress.fetchPosts(
params: wp.ParamsPostList(
context: wp.WordPressContext.view,
pageNum: 1,
perPage: 20,
order: wp.Order.desc,
orderBy: wp.PostsOrderBy.date,
),
);
```

### 5. Fetch Users

```dart
Future<List<wp.User>> users = wordPress.fetchUsers(
params: wp.ParamsUserList(
context: wp.WordPressContext.view,
pageNum: 1,
perPage: 30,
order: wp.Order.asc,
orderBy: wp.UsersOrderBy.name,
role: wp.UserRole.subscriber,
),
);
```

### 6. Fetch Comments

```dart
Future<List<wp.Comment>> comments = wordPress.fetchComments(
params: wp.ParamsCommentList(
context: wp.WordPressContext.view,
pageNum: 1,
perPage: 30,
includePostIDs: [1],
),
);
```

## Future Work
1. Implementing OAuth 2.0 authentication.



88 changes: 69 additions & 19 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -51,59 +51,109 @@ class PostsBuilder extends StatefulWidget {

class PostsBuilderState extends State<PostsBuilder> {
wp.WordPress wordPress;
Future<List<wp.Posts>> posts;
Future<List<wp.Users>> users;
Future<List<wp.Post>> posts;
Future<List<wp.User>> users;

@override
void initState() {
super.initState();

wordPress = wp.WordPress(
'https://wordpress.dsoft.website', wp.WordpressContext.view);
try {
wordPress = wp.WordPress(
baseUrl: 'http://192.168.6.165',
authenticator: wp.WordPressAuthenticator.ApplicationPasswords,
adminName: 'admin',
adminKey: 'EOjD JsYA hKfM RHNI vufW hyUX',
);
} catch (err) {
print(err.toString());
}

/* Future<wp.User> response = wordPress.authenticateUser(
username: 'username',
password: 'password',
);
Future<wp.AuthResponse> auth = wordPress.authenticateUser(
username: 'admin ', password: 'mypassword@123');
response.then((user) {
print(user.toString());
}).catchError((err) {
print(err.toString());
});*/

Future<List<wp.User>> users = wordPress.fetchUsers(
params: wp.ParamsUserList(
context: wp.WordPressContext.view,
pageNum: 1,
perPage: 30,
order: wp.Order.asc,
orderBy: wp.UsersOrderBy.name,
),
);

auth.then((response) {
fetchPosts();
users.then((response) {
print(response);
}).catchError((err) {
print(err.message);
print(err.toString());
});

Future<List<wp.Comment>> comments = wordPress.fetchComments(
params: wp.ParamsCommentList(
context: wp.WordPressContext.view,
pageNum: 1,
perPage: 30,
),
);

comments.then((response) {
print(response);
}).catchError((err) {
print(err.toString());
});
}

void fetchPosts()
{
void fetchPosts() {
setState(() {
posts = wordPress.fetchPosts();
posts = wordPress.fetchPosts(params: wp.ParamsPostList());
});
}

void fetchUsers()
{
void fetchUsers() {
setState(() {
users = wordPress.fetchUsers();
users = wordPress.fetchUsers(params: wp.ParamsUserList());
});
}

@override
Widget build(BuildContext context) {
return FutureBuilder<List<wp.Posts>>(
return FutureBuilder<List<wp.Post>>(
future: posts,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.separated(
itemBuilder: (context, i) {
return Text(snapshot.data[i].title.rendered);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
snapshot.data[i].title.rendered,
style: Theme.of(context).textTheme.title,
),
Text(
snapshot.data[i].content.rendered,
),
],
);
},
separatorBuilder: (context, i) {
return Divider();
},
itemCount: snapshot.data.length,
);
} else if (snapshot.hasError) {
wp.WordpressError err = snapshot.error as wp.WordpressError;
return Text(err.message);
return Text(
snapshot.error.toString(),
style: TextStyle(color: Colors.red),
);
}
return CircularProgressIndicator();
},
Expand Down
122 changes: 122 additions & 0 deletions lib/constants.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
const URL_WP_BASE = '/wp-json/wp/v2';
const URL_JWT_BASE = '/wp-json/jwt-auth/v1';

const URL_JWT_TOKEN = '$URL_JWT_BASE/token';
const URL_JWT_TOKEN_VALIDATE = '$URL_JWT_BASE/token/validate';

const URL_POSTS = '$URL_WP_BASE/posts';
const URL_USERS = '$URL_WP_BASE/users';
const URL_COMMENTS = '$URL_WP_BASE/comments';

enum WordPressAuthenticator {
JWT,
ApplicationPasswords,
}
enum WordPressContext { view, embed, edit }

enum Order {
asc,
desc,
}

enum PostsOrderBy {
author,
date,
id,
include,
modified,
parent,
relevance,
slug,
title,
}
enum PostStatus {
publish,
future,
draft,
pending,
private,
}
enum PostCommentStatus {
open,
closed,
}
enum PostPingStatus {
open,
closed,
}
enum ObjectFormat {
standard,
aside,
chat,
gallery,
link,
image,
quote,
status,
video,
audio,
}

enum UsersOrderBy {
id,
include,
name,
registered_date,
slug,
email,
url,
}
enum UserRole {
subscriber,
contributor,
author,
editor,
administrator,
}

enum CommentsOrderBy {
date,
date_gmt,
id,
include,
post,
parent,
type,
}
enum CommentStatus {
all,
approve,
hold,
spam,
trash,
}
enum CommentType {
comment,
//TODO: Add all comment types
}

/// Converts an enum string to enum value name.
String enumStringToName(String enumString) {
return enumString.split('.')[1];
}

/// Formats a list of [items] to a comma(,) separated string to pass it as a
/// URL parameter.
String listToUrlString<T>(List<T> items) {
if (items == null || items.length == 0) return '';

return items.join(',');
}

/// Formats a [Map] of parameters to a string of URL friendly parameters.
String constructUrlParams(Map<String, String> params) {
StringBuffer p = new StringBuffer('/?');
params.forEach((key, value) {
if (value != '') {
p.write('$key=$value');
p.write('&');
}
});
return p.toString();
}
Loading

0 comments on commit 96c6b18

Please sign in to comment.